3 * Representation of a title within %MediaWiki.
7 * This program is free software; you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation; either version 2 of the License, or
10 * (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License along
18 * with this program; if not, write to the Free Software Foundation, Inc.,
19 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
20 * http://www.gnu.org/copyleft/gpl.html
25 use Wikimedia\Rdbms\Database
;
26 use Wikimedia\Rdbms\IDatabase
;
27 use MediaWiki\Linker\LinkTarget
;
28 use MediaWiki\Interwiki\InterwikiLookup
;
29 use MediaWiki\MediaWikiServices
;
32 * Represents a title within MediaWiki.
33 * Optionally may contain an interwiki designation or namespace.
34 * @note This class can fetch various kinds of data from the database;
35 * however, it does so inefficiently.
36 * @note Consider using a TitleValue object instead. TitleValue is more lightweight
37 * and does not rely on global state or the database.
39 class Title
implements LinkTarget
, IDBAccessObject
{
40 /** @var MapCacheLRU|null */
41 private static $titleCache = null;
44 * Title::newFromText maintains a cache to avoid expensive re-normalization of
45 * commonly used titles. On a batch operation this can become a memory leak
46 * if not bounded. After hitting this many titles reset the cache.
48 const CACHE_MAX
= 1000;
51 * Used to be GAID_FOR_UPDATE define. Used with getArticleID() and friends
52 * to use the master DB
54 const GAID_FOR_UPDATE
= 1;
57 * @name Private member variables
58 * Please use the accessor functions instead.
63 /** @var string Text form (spaces not underscores) of the main part */
64 public $mTextform = '';
66 /** @var string URL-encoded form of the main part */
67 public $mUrlform = '';
69 /** @var string Main part with underscores */
70 public $mDbkeyform = '';
72 /** @var string Database key with the initial letter in the case specified by the user */
73 protected $mUserCaseDBKey;
75 /** @var int Namespace index, i.e. one of the NS_xxxx constants */
76 public $mNamespace = NS_MAIN
;
78 /** @var string Interwiki prefix */
79 public $mInterwiki = '';
81 /** @var bool Was this Title created from a string with a local interwiki prefix? */
82 private $mLocalInterwiki = false;
84 /** @var string Title fragment (i.e. the bit after the #) */
85 public $mFragment = '';
87 /** @var int Article ID, fetched from the link cache on demand */
88 public $mArticleID = -1;
90 /** @var bool|int ID of most recent revision */
91 protected $mLatestID = false;
94 * @var bool|string ID of the page's content model, i.e. one of the
95 * CONTENT_MODEL_XXX constants
97 private $mContentModel = false;
100 * @var bool If a content model was forced via setContentModel()
101 * this will be true to avoid having other code paths reset it
103 private $mForcedContentModel = false;
105 /** @var int Estimated number of revisions; null of not loaded */
106 private $mEstimateRevisions;
108 /** @var array Array of groups allowed to edit this article */
109 public $mRestrictions = [];
112 * @var string|bool Comma-separated set of permission keys
113 * indicating who can move or edit the page from the page table, (pre 1.10) rows.
114 * Edit and move sections are separated by a colon
115 * Example: "edit=autoconfirmed,sysop:move=sysop"
117 protected $mOldRestrictions = false;
119 /** @var bool Cascade restrictions on this page to included templates and images? */
120 public $mCascadeRestriction;
122 /** Caching the results of getCascadeProtectionSources */
123 public $mCascadingRestrictions;
125 /** @var array When do the restrictions on this page expire? */
126 protected $mRestrictionsExpiry = [];
128 /** @var bool Are cascading restrictions in effect on this page? */
129 protected $mHasCascadingRestrictions;
131 /** @var array Where are the cascading restrictions coming from on this page? */
132 public $mCascadeSources;
134 /** @var bool Boolean for initialisation on demand */
135 public $mRestrictionsLoaded = false;
138 * Text form including namespace/interwiki, initialised on demand
140 * Only public to share cache with TitleFormatter
145 public $prefixedText = null;
147 /** @var mixed Cached value for getTitleProtection (create protection) */
148 public $mTitleProtection;
151 * @var int Namespace index when there is no namespace. Don't change the
152 * following default, NS_MAIN is hardcoded in several places. See T2696.
153 * Zero except in {{transclusion}} tags.
155 public $mDefaultNamespace = NS_MAIN
;
157 /** @var int The page length, 0 for special pages */
158 protected $mLength = -1;
160 /** @var null Is the article at this title a redirect? */
161 public $mRedirect = null;
163 /** @var array Associative array of user ID -> timestamp/false */
164 private $mNotificationTimestamp = [];
166 /** @var bool Whether a page has any subpages */
167 private $mHasSubpages;
169 /** @var bool The (string) language code of the page's language and content code. */
170 private $mPageLanguage = false;
172 /** @var string|bool|null The page language code from the database, null if not saved in
173 * the database or false if not loaded, yet. */
174 private $mDbPageLanguage = false;
176 /** @var TitleValue|null A corresponding TitleValue object */
177 private $mTitleValue = null;
179 /** @var bool|null Would deleting this page be a big deletion? */
180 private $mIsBigDeletion = null;
184 * B/C kludge: provide a TitleParser for use by Title.
185 * Ideally, Title would have no methods that need this.
186 * Avoid usage of this singleton by using TitleValue
187 * and the associated services when possible.
189 * @return TitleFormatter
191 private static function getTitleFormatter() {
192 return MediaWikiServices
::getInstance()->getTitleFormatter();
196 * B/C kludge: provide an InterwikiLookup for use by Title.
197 * Ideally, Title would have no methods that need this.
198 * Avoid usage of this singleton by using TitleValue
199 * and the associated services when possible.
201 * @return InterwikiLookup
203 private static function getInterwikiLookup() {
204 return MediaWikiServices
::getInstance()->getInterwikiLookup();
210 function __construct() {
214 * Create a new Title from a prefixed DB key
216 * @param string $key The database key, which has underscores
217 * instead of spaces, possibly including namespace and
219 * @return Title|null Title, or null on an error
221 public static function newFromDBkey( $key ) {
223 $t->mDbkeyform
= $key;
226 $t->secureAndSplit();
228 } catch ( MalformedTitleException
$ex ) {
234 * Create a new Title from a TitleValue
236 * @param TitleValue $titleValue Assumed to be safe.
240 public static function newFromTitleValue( TitleValue
$titleValue ) {
241 return self
::newFromLinkTarget( $titleValue );
245 * Create a new Title from a LinkTarget
247 * @param LinkTarget $linkTarget Assumed to be safe.
251 public static function newFromLinkTarget( LinkTarget
$linkTarget ) {
252 if ( $linkTarget instanceof Title
) {
253 // Special case if it's already a Title object
256 return self
::makeTitle(
257 $linkTarget->getNamespace(),
258 $linkTarget->getText(),
259 $linkTarget->getFragment(),
260 $linkTarget->getInterwiki()
265 * Create a new Title from text, such as what one would find in a link. De-
266 * codes any HTML entities in the text.
268 * Title objects returned by this method are guaranteed to be valid, and
269 * thus return true from the isValid() method.
271 * @param string|int|null $text The link text; spaces, prefixes, and an
272 * initial ':' indicating the main namespace are accepted.
273 * @param int $defaultNamespace The namespace to use if none is specified
274 * by a prefix. If you want to force a specific namespace even if
275 * $text might begin with a namespace prefix, use makeTitle() or
277 * @throws InvalidArgumentException
278 * @return Title|null Title or null on an error.
280 public static function newFromText( $text, $defaultNamespace = NS_MAIN
) {
281 // DWIM: Integers can be passed in here when page titles are used as array keys.
282 if ( $text !== null && !is_string( $text ) && !is_int( $text ) ) {
283 throw new InvalidArgumentException( '$text must be a string.' );
285 if ( $text === null ) {
290 return self
::newFromTextThrow( (string)$text, $defaultNamespace );
291 } catch ( MalformedTitleException
$ex ) {
297 * Like Title::newFromText(), but throws MalformedTitleException when the title is invalid,
298 * rather than returning null.
300 * The exception subclasses encode detailed information about why the title is invalid.
302 * Title objects returned by this method are guaranteed to be valid, and
303 * thus return true from the isValid() method.
305 * @see Title::newFromText
308 * @param string $text Title text to check
309 * @param int $defaultNamespace
310 * @throws MalformedTitleException If the title is invalid
313 public static function newFromTextThrow( $text, $defaultNamespace = NS_MAIN
) {
314 if ( is_object( $text ) ) {
315 throw new MWException( '$text must be a string, given an object' );
316 } elseif ( $text === null ) {
317 // Legacy code relies on MalformedTitleException being thrown in this case
318 // (happens when URL with no title in it is parsed). TODO fix
319 throw new MalformedTitleException( 'title-invalid-empty' );
322 $titleCache = self
::getTitleCache();
324 // Wiki pages often contain multiple links to the same page.
325 // Title normalization and parsing can become expensive on pages with many
326 // links, so we can save a little time by caching them.
327 // In theory these are value objects and won't get changed...
328 if ( $defaultNamespace == NS_MAIN
) {
329 $t = $titleCache->get( $text );
335 // Convert things like é ā or 〗 into normalized (T16952) text
336 $filteredText = Sanitizer
::decodeCharReferencesAndNormalize( $text );
339 $t->mDbkeyform
= strtr( $filteredText, ' ', '_' );
340 $t->mDefaultNamespace
= (int)$defaultNamespace;
342 $t->secureAndSplit();
343 if ( $defaultNamespace == NS_MAIN
) {
344 $titleCache->set( $text, $t );
350 * THIS IS NOT THE FUNCTION YOU WANT. Use Title::newFromText().
352 * Example of wrong and broken code:
353 * $title = Title::newFromURL( $wgRequest->getVal( 'title' ) );
355 * Example of right code:
356 * $title = Title::newFromText( $wgRequest->getVal( 'title' ) );
358 * Create a new Title from URL-encoded text. Ensures that
359 * the given title's length does not exceed the maximum.
361 * @param string $url The title, as might be taken from a URL
362 * @return Title|null The new object, or null on an error
364 public static function newFromURL( $url ) {
367 # For compatibility with old buggy URLs. "+" is usually not valid in titles,
368 # but some URLs used it as a space replacement and they still come
369 # from some external search tools.
370 if ( strpos( self
::legalChars(), '+' ) === false ) {
371 $url = strtr( $url, '+', ' ' );
374 $t->mDbkeyform
= strtr( $url, ' ', '_' );
377 $t->secureAndSplit();
379 } catch ( MalformedTitleException
$ex ) {
385 * @return MapCacheLRU
387 private static function getTitleCache() {
388 if ( self
::$titleCache === null ) {
389 self
::$titleCache = new MapCacheLRU( self
::CACHE_MAX
);
391 return self
::$titleCache;
395 * Returns a list of fields that are to be selected for initializing Title
396 * objects or LinkCache entries. Uses $wgContentHandlerUseDB to determine
397 * whether to include page_content_model.
401 protected static function getSelectFields() {
402 global $wgContentHandlerUseDB, $wgPageLanguageUseDB;
405 'page_namespace', 'page_title', 'page_id',
406 'page_len', 'page_is_redirect', 'page_latest',
409 if ( $wgContentHandlerUseDB ) {
410 $fields[] = 'page_content_model';
413 if ( $wgPageLanguageUseDB ) {
414 $fields[] = 'page_lang';
421 * Create a new Title from an article ID
423 * @param int $id The page_id corresponding to the Title to create
424 * @param int $flags Use Title::GAID_FOR_UPDATE to use master
425 * @return Title|null The new object, or null on an error
427 public static function newFromID( $id, $flags = 0 ) {
428 $db = ( $flags & self
::GAID_FOR_UPDATE
) ?
wfGetDB( DB_MASTER
) : wfGetDB( DB_REPLICA
);
429 $row = $db->selectRow(
431 self
::getSelectFields(),
432 [ 'page_id' => $id ],
435 if ( $row !== false ) {
436 $title = self
::newFromRow( $row );
445 * Make an array of titles from an array of IDs
447 * @param int[] $ids Array of IDs
448 * @return Title[] Array of Titles
450 public static function newFromIDs( $ids ) {
451 if ( !count( $ids ) ) {
454 $dbr = wfGetDB( DB_REPLICA
);
458 self
::getSelectFields(),
459 [ 'page_id' => $ids ],
464 foreach ( $res as $row ) {
465 $titles[] = self
::newFromRow( $row );
471 * Make a Title object from a DB row
473 * @param stdClass $row Object database row (needs at least page_title,page_namespace)
474 * @return Title Corresponding Title
476 public static function newFromRow( $row ) {
477 $t = self
::makeTitle( $row->page_namespace
, $row->page_title
);
478 $t->loadFromRow( $row );
483 * Load Title object fields from a DB row.
484 * If false is given, the title will be treated as non-existing.
486 * @param stdClass|bool $row Database row
488 public function loadFromRow( $row ) {
489 if ( $row ) { // page found
490 if ( isset( $row->page_id
) ) {
491 $this->mArticleID
= (int)$row->page_id
;
493 if ( isset( $row->page_len
) ) {
494 $this->mLength
= (int)$row->page_len
;
496 if ( isset( $row->page_is_redirect
) ) {
497 $this->mRedirect
= (bool)$row->page_is_redirect
;
499 if ( isset( $row->page_latest
) ) {
500 $this->mLatestID
= (int)$row->page_latest
;
502 if ( !$this->mForcedContentModel
&& isset( $row->page_content_model
) ) {
503 $this->mContentModel
= (string)$row->page_content_model
;
504 } elseif ( !$this->mForcedContentModel
) {
505 $this->mContentModel
= false; # initialized lazily in getContentModel()
507 if ( isset( $row->page_lang
) ) {
508 $this->mDbPageLanguage
= (string)$row->page_lang
;
510 if ( isset( $row->page_restrictions
) ) {
511 $this->mOldRestrictions
= $row->page_restrictions
;
513 } else { // page not found
514 $this->mArticleID
= 0;
516 $this->mRedirect
= false;
517 $this->mLatestID
= 0;
518 if ( !$this->mForcedContentModel
) {
519 $this->mContentModel
= false; # initialized lazily in getContentModel()
525 * Create a new Title from a namespace index and a DB key.
527 * It's assumed that $ns and $title are safe, for instance when
528 * they came directly from the database or a special page name,
529 * not from user input.
531 * No validation is applied. For convenience, spaces are normalized
532 * to underscores, so that e.g. user_text fields can be used directly.
534 * @note This method may return Title objects that are "invalid"
535 * according to the isValid() method. This is usually caused by
536 * configuration changes: e.g. a namespace that was once defined is
537 * no longer configured, or a character that was once allowed in
538 * titles is now forbidden.
540 * @param int $ns The namespace of the article
541 * @param string $title The unprefixed database key form
542 * @param string $fragment The link fragment (after the "#")
543 * @param string $interwiki The interwiki prefix
544 * @return Title The new object
546 public static function makeTitle( $ns, $title, $fragment = '', $interwiki = '' ) {
548 $t->mInterwiki
= $interwiki;
549 $t->mFragment
= $fragment;
550 $t->mNamespace
= $ns = (int)$ns;
551 $t->mDbkeyform
= strtr( $title, ' ', '_' );
552 $t->mArticleID
= ( $ns >= 0 ) ?
-1 : 0;
553 $t->mUrlform
= wfUrlencode( $t->mDbkeyform
);
554 $t->mTextform
= strtr( $title, '_', ' ' );
555 $t->mContentModel
= false; # initialized lazily in getContentModel()
560 * Create a new Title from a namespace index and a DB key.
561 * The parameters will be checked for validity, which is a bit slower
562 * than makeTitle() but safer for user-provided data.
564 * Title objects returned by makeTitleSafe() are guaranteed to be valid,
565 * that is, they return true from the isValid() method. If no valid Title
566 * can be constructed from the input, this method returns null.
568 * @param int $ns The namespace of the article
569 * @param string $title Database key form
570 * @param string $fragment The link fragment (after the "#")
571 * @param string $interwiki Interwiki prefix
572 * @return Title|null The new object, or null on an error
574 public static function makeTitleSafe( $ns, $title, $fragment = '', $interwiki = '' ) {
575 // NOTE: ideally, this would just call makeTitle() and then isValid(),
576 // but presently, that means more overhead on a potential performance hotspot.
578 if ( !MWNamespace
::exists( $ns ) ) {
583 $t->mDbkeyform
= self
::makeName( $ns, $title, $fragment, $interwiki, true );
586 $t->secureAndSplit();
588 } catch ( MalformedTitleException
$ex ) {
594 * Create a new Title for the Main Page
596 * @return Title The new object
598 public static function newMainPage() {
599 $title = self
::newFromText( wfMessage( 'mainpage' )->inContentLanguage()->text() );
600 // Don't give fatal errors if the message is broken
602 $title = self
::newFromText( 'Main Page' );
608 * Get the prefixed DB key associated with an ID
610 * @param int $id The page_id of the article
611 * @return Title|null An object representing the article, or null if no such article was found
613 public static function nameOf( $id ) {
614 $dbr = wfGetDB( DB_REPLICA
);
616 $s = $dbr->selectRow(
618 [ 'page_namespace', 'page_title' ],
619 [ 'page_id' => $id ],
622 if ( $s === false ) {
626 $n = self
::makeName( $s->page_namespace
, $s->page_title
);
631 * Get a regex character class describing the legal characters in a link
633 * @return string The list of characters, not delimited
635 public static function legalChars() {
636 global $wgLegalTitleChars;
637 return $wgLegalTitleChars;
641 * Utility method for converting a character sequence from bytes to Unicode.
643 * Primary usecase being converting $wgLegalTitleChars to a sequence usable in
644 * javascript, as PHP uses UTF-8 bytes where javascript uses Unicode code units.
646 * @param string $byteClass
649 public static function convertByteClassToUnicodeClass( $byteClass ) {
650 $length = strlen( $byteClass );
652 $x0 = $x1 = $x2 = '';
654 $d0 = $d1 = $d2 = '';
655 // Decoded integer codepoints
656 $ord0 = $ord1 = $ord2 = 0;
658 $r0 = $r1 = $r2 = '';
662 $allowUnicode = false;
663 for ( $pos = 0; $pos < $length; $pos++
) {
664 // Shift the queues down
673 // Load the current input token and decoded values
674 $inChar = $byteClass[$pos];
675 if ( $inChar == '\\' ) {
676 if ( preg_match( '/x([0-9a-fA-F]{2})/A', $byteClass, $m, 0, $pos +
1 ) ) {
677 $x0 = $inChar . $m[0];
678 $d0 = chr( hexdec( $m[1] ) );
679 $pos +
= strlen( $m[0] );
680 } elseif ( preg_match( '/[0-7]{3}/A', $byteClass, $m, 0, $pos +
1 ) ) {
681 $x0 = $inChar . $m[0];
682 $d0 = chr( octdec( $m[0] ) );
683 $pos +
= strlen( $m[0] );
684 } elseif ( $pos +
1 >= $length ) {
687 $d0 = $byteClass[$pos +
1];
695 // Load the current re-encoded value
696 if ( $ord0 < 32 ||
$ord0 == 0x7f ) {
697 $r0 = sprintf( '\x%02x', $ord0 );
698 } elseif ( $ord0 >= 0x80 ) {
699 // Allow unicode if a single high-bit character appears
700 $r0 = sprintf( '\x%02x', $ord0 );
701 $allowUnicode = true;
702 } elseif ( strpos( '-\\[]^', $d0 ) !== false ) {
708 if ( $x0 !== '' && $x1 === '-' && $x2 !== '' ) {
710 if ( $ord2 > $ord0 ) {
712 } elseif ( $ord0 >= 0x80 ) {
714 $allowUnicode = true;
715 if ( $ord2 < 0x80 ) {
716 // Keep the non-unicode section of the range
723 // Reset state to the initial value
724 $x0 = $x1 = $d0 = $d1 = $r0 = $r1 = '';
725 } elseif ( $ord2 < 0x80 ) {
730 if ( $ord1 < 0x80 ) {
733 if ( $ord0 < 0x80 ) {
736 if ( $allowUnicode ) {
737 $out .= '\u0080-\uFFFF';
743 * Make a prefixed DB key from a DB key and a namespace index
745 * @param int $ns Numerical representation of the namespace
746 * @param string $title The DB key form the title
747 * @param string $fragment The link fragment (after the "#")
748 * @param string $interwiki The interwiki prefix
749 * @param bool $canonicalNamespace If true, use the canonical name for
750 * $ns instead of the localized version.
751 * @return string The prefixed form of the title
753 public static function makeName( $ns, $title, $fragment = '', $interwiki = '',
754 $canonicalNamespace = false
756 if ( $canonicalNamespace ) {
757 $namespace = MWNamespace
::getCanonicalName( $ns );
759 $namespace = MediaWikiServices
::getInstance()->getContentLanguage()->getNsText( $ns );
761 $name = $namespace == '' ?
$title : "$namespace:$title";
762 if ( strval( $interwiki ) != '' ) {
763 $name = "$interwiki:$name";
765 if ( strval( $fragment ) != '' ) {
766 $name .= '#' . $fragment;
772 * Callback for usort() to do title sorts by (namespace, title)
774 * @param LinkTarget $a
775 * @param LinkTarget $b
777 * @return int Result of string comparison, or namespace comparison
779 public static function compare( LinkTarget
$a, LinkTarget
$b ) {
780 return $a->getNamespace() <=> $b->getNamespace()
781 ?
: strcmp( $a->getText(), $b->getText() );
785 * Returns true if the title is valid, false if it is invalid.
787 * Valid titles can be round-tripped via makeTitleSafe() and newFromText().
788 * Invalid titles may get returned from makeTitle(), and it may be useful to
789 * allow them to exist, e.g. in order to process log entries about pages in
790 * namespaces that belong to extensions that are no longer installed.
792 * @note This method is relatively expensive. When constructing Title
793 * objects that need to be valid, use an instantiator method that is guaranteed
794 * to return valid titles, such as makeTitleSafe() or newFromText().
798 public function isValid() {
799 if ( !MWNamespace
::exists( $this->mNamespace
) ) {
804 $parser = MediaWikiServices
::getInstance()->getTitleParser();
805 $parser->parseTitle( $this->mDbkeyform
, $this->mNamespace
);
807 } catch ( MalformedTitleException
$ex ) {
813 * Determine whether the object refers to a page within
814 * this project (either this wiki or a wiki with a local
815 * interwiki, see https://www.mediawiki.org/wiki/Manual:Interwiki_table#iw_local )
817 * @return bool True if this is an in-project interwiki link or a wikilink, false otherwise
819 public function isLocal() {
820 if ( $this->isExternal() ) {
821 $iw = self
::getInterwikiLookup()->fetch( $this->mInterwiki
);
823 return $iw->isLocal();
830 * Is this Title interwiki?
834 public function isExternal() {
835 return $this->mInterwiki
!== '';
839 * Get the interwiki prefix
841 * Use Title::isExternal to check if a interwiki is set
843 * @return string Interwiki prefix
845 public function getInterwiki() {
846 return $this->mInterwiki
;
850 * Was this a local interwiki link?
854 public function wasLocalInterwiki() {
855 return $this->mLocalInterwiki
;
859 * Determine whether the object refers to a page within
860 * this project and is transcludable.
862 * @return bool True if this is transcludable
864 public function isTrans() {
865 if ( !$this->isExternal() ) {
869 return self
::getInterwikiLookup()->fetch( $this->mInterwiki
)->isTranscludable();
873 * Returns the DB name of the distant wiki which owns the object.
875 * @return string|false The DB name
877 public function getTransWikiID() {
878 if ( !$this->isExternal() ) {
882 return self
::getInterwikiLookup()->fetch( $this->mInterwiki
)->getWikiID();
886 * Get a TitleValue object representing this Title.
888 * @note Not all valid Titles have a corresponding valid TitleValue
889 * (e.g. TitleValues cannot represent page-local links that have a
890 * fragment but no title text).
892 * @return TitleValue|null
894 public function getTitleValue() {
895 if ( $this->mTitleValue
=== null ) {
897 $this->mTitleValue
= new TitleValue(
903 } catch ( InvalidArgumentException
$ex ) {
904 wfDebug( __METHOD__
. ': Can\'t create a TitleValue for [[' .
905 $this->getPrefixedText() . ']]: ' . $ex->getMessage() . "\n" );
909 return $this->mTitleValue
;
913 * Get the text form (spaces not underscores) of the main part
915 * @return string Main part of the title
917 public function getText() {
918 return $this->mTextform
;
922 * Get the URL-encoded form of the main part
924 * @return string Main part of the title, URL-encoded
926 public function getPartialURL() {
927 return $this->mUrlform
;
931 * Get the main part with underscores
933 * @return string Main part of the title, with underscores
935 public function getDBkey() {
936 return $this->mDbkeyform
;
940 * Get the DB key with the initial letter case as specified by the user
941 * @deprecated since 1.33; please use Title::getDBKey() instead
943 * @return string DB key
945 function getUserCaseDBKey() {
946 if ( !is_null( $this->mUserCaseDBKey
) ) {
947 return $this->mUserCaseDBKey
;
949 // If created via makeTitle(), $this->mUserCaseDBKey is not set.
950 return $this->mDbkeyform
;
955 * Get the namespace index, i.e. one of the NS_xxxx constants.
957 * @return int Namespace index
959 public function getNamespace() {
960 return $this->mNamespace
;
964 * Get the page's content model id, see the CONTENT_MODEL_XXX constants.
966 * @todo Deprecate this in favor of SlotRecord::getModel()
968 * @param int $flags A bit field; may be Title::GAID_FOR_UPDATE to select for update
969 * @return string Content model id
971 public function getContentModel( $flags = 0 ) {
972 if ( !$this->mForcedContentModel
973 && ( !$this->mContentModel ||
$flags === self
::GAID_FOR_UPDATE
)
974 && $this->getArticleID( $flags )
976 $linkCache = MediaWikiServices
::getInstance()->getLinkCache();
977 $linkCache->addLinkObj( $this ); # in case we already had an article ID
978 $this->mContentModel
= $linkCache->getGoodLinkFieldObj( $this, 'model' );
981 if ( !$this->mContentModel
) {
982 $this->mContentModel
= ContentHandler
::getDefaultModelFor( $this );
985 return $this->mContentModel
;
989 * Convenience method for checking a title's content model name
991 * @param string $id The content model ID (use the CONTENT_MODEL_XXX constants).
992 * @return bool True if $this->getContentModel() == $id
994 public function hasContentModel( $id ) {
995 return $this->getContentModel() == $id;
999 * Set a proposed content model for the page for permissions
1000 * checking. This does not actually change the content model
1003 * Additionally, you should make sure you've checked
1004 * ContentHandler::canBeUsedOn() first.
1007 * @param string $model CONTENT_MODEL_XXX constant
1009 public function setContentModel( $model ) {
1010 $this->mContentModel
= $model;
1011 $this->mForcedContentModel
= true;
1015 * Get the namespace text
1017 * @return string|false Namespace text
1019 public function getNsText() {
1020 if ( $this->isExternal() ) {
1021 // This probably shouldn't even happen, except for interwiki transclusion.
1022 // If possible, use the canonical name for the foreign namespace.
1023 $nsText = MWNamespace
::getCanonicalName( $this->mNamespace
);
1024 if ( $nsText !== false ) {
1030 $formatter = self
::getTitleFormatter();
1031 return $formatter->getNamespaceName( $this->mNamespace
, $this->mDbkeyform
);
1032 } catch ( InvalidArgumentException
$ex ) {
1033 wfDebug( __METHOD__
. ': ' . $ex->getMessage() . "\n" );
1039 * Get the namespace text of the subject (rather than talk) page
1041 * @return string Namespace text
1043 public function getSubjectNsText() {
1044 return MediaWikiServices
::getInstance()->getContentLanguage()->
1045 getNsText( MWNamespace
::getSubject( $this->mNamespace
) );
1049 * Get the namespace text of the talk page
1051 * @return string Namespace text
1053 public function getTalkNsText() {
1054 return MediaWikiServices
::getInstance()->getContentLanguage()->
1055 getNsText( MWNamespace
::getTalk( $this->mNamespace
) );
1059 * Can this title have a corresponding talk page?
1061 * @see MWNamespace::hasTalkNamespace
1064 * @return bool True if this title either is a talk page or can have a talk page associated.
1066 public function canHaveTalkPage() {
1067 return MWNamespace
::hasTalkNamespace( $this->mNamespace
);
1071 * Is this in a namespace that allows actual pages?
1075 public function canExist() {
1076 return $this->mNamespace
>= NS_MAIN
;
1080 * Can this title be added to a user's watchlist?
1084 public function isWatchable() {
1085 return !$this->isExternal() && MWNamespace
::isWatchable( $this->mNamespace
);
1089 * Returns true if this is a special page.
1093 public function isSpecialPage() {
1094 return $this->mNamespace
== NS_SPECIAL
;
1098 * Returns true if this title resolves to the named special page
1100 * @param string $name The special page name
1103 public function isSpecial( $name ) {
1104 if ( $this->isSpecialPage() ) {
1105 list( $thisName, /* $subpage */ ) =
1106 MediaWikiServices
::getInstance()->getSpecialPageFactory()->
1107 resolveAlias( $this->mDbkeyform
);
1108 if ( $name == $thisName ) {
1116 * If the Title refers to a special page alias which is not the local default, resolve
1117 * the alias, and localise the name as necessary. Otherwise, return $this
1121 public function fixSpecialName() {
1122 if ( $this->isSpecialPage() ) {
1123 $spFactory = MediaWikiServices
::getInstance()->getSpecialPageFactory();
1124 list( $canonicalName, $par ) = $spFactory->resolveAlias( $this->mDbkeyform
);
1125 if ( $canonicalName ) {
1126 $localName = $spFactory->getLocalNameFor( $canonicalName, $par );
1127 if ( $localName != $this->mDbkeyform
) {
1128 return self
::makeTitle( NS_SPECIAL
, $localName );
1136 * Returns true if the title is inside the specified namespace.
1138 * Please make use of this instead of comparing to getNamespace()
1139 * This function is much more resistant to changes we may make
1140 * to namespaces than code that makes direct comparisons.
1141 * @param int $ns The namespace
1145 public function inNamespace( $ns ) {
1146 return MWNamespace
::equals( $this->mNamespace
, $ns );
1150 * Returns true if the title is inside one of the specified namespaces.
1152 * @param int|int[] $namespaces,... The namespaces to check for
1156 public function inNamespaces( /* ... */ ) {
1157 $namespaces = func_get_args();
1158 if ( count( $namespaces ) > 0 && is_array( $namespaces[0] ) ) {
1159 $namespaces = $namespaces[0];
1162 foreach ( $namespaces as $ns ) {
1163 if ( $this->inNamespace( $ns ) ) {
1172 * Returns true if the title has the same subject namespace as the
1173 * namespace specified.
1174 * For example this method will take NS_USER and return true if namespace
1175 * is either NS_USER or NS_USER_TALK since both of them have NS_USER
1176 * as their subject namespace.
1178 * This is MUCH simpler than individually testing for equivalence
1179 * against both NS_USER and NS_USER_TALK, and is also forward compatible.
1184 public function hasSubjectNamespace( $ns ) {
1185 return MWNamespace
::subjectEquals( $this->mNamespace
, $ns );
1189 * Is this Title in a namespace which contains content?
1190 * In other words, is this a content page, for the purposes of calculating
1195 public function isContentPage() {
1196 return MWNamespace
::isContent( $this->mNamespace
);
1200 * Would anybody with sufficient privileges be able to move this page?
1201 * Some pages just aren't movable.
1205 public function isMovable() {
1206 if ( !MWNamespace
::isMovable( $this->mNamespace
) ||
$this->isExternal() ) {
1207 // Interwiki title or immovable namespace. Hooks don't get to override here
1212 Hooks
::run( 'TitleIsMovable', [ $this, &$result ] );
1217 * Is this the mainpage?
1218 * @note Title::newFromText seems to be sufficiently optimized by the title
1219 * cache that we don't need to over-optimize by doing direct comparisons and
1220 * accidentally creating new bugs where $title->equals( Title::newFromText() )
1221 * ends up reporting something differently than $title->isMainPage();
1226 public function isMainPage() {
1227 return $this->equals( self
::newMainPage() );
1231 * Is this a subpage?
1235 public function isSubpage() {
1236 return MWNamespace
::hasSubpages( $this->mNamespace
)
1237 ?
strpos( $this->getText(), '/' ) !== false
1242 * Is this a conversion table for the LanguageConverter?
1246 public function isConversionTable() {
1247 // @todo ConversionTable should become a separate content model.
1249 return $this->mNamespace
== NS_MEDIAWIKI
&&
1250 strpos( $this->getText(), 'Conversiontable/' ) === 0;
1254 * Does that page contain wikitext, or it is JS, CSS or whatever?
1258 public function isWikitextPage() {
1259 return $this->hasContentModel( CONTENT_MODEL_WIKITEXT
);
1263 * Could this MediaWiki namespace page contain custom CSS, JSON, or JavaScript for the
1264 * global UI. This is generally true for pages in the MediaWiki namespace having
1265 * CONTENT_MODEL_CSS, CONTENT_MODEL_JSON, or CONTENT_MODEL_JAVASCRIPT.
1267 * This method does *not* return true for per-user JS/JSON/CSS. Use isUserConfigPage()
1270 * Note that this method should not return true for pages that contain and show
1271 * "inactive" CSS, JSON, or JS.
1276 public function isSiteConfigPage() {
1278 $this->isSiteCssConfigPage()
1279 ||
$this->isSiteJsonConfigPage()
1280 ||
$this->isSiteJsConfigPage()
1285 * Is this a "config" (.css, .json, or .js) sub-page of a user page?
1290 public function isUserConfigPage() {
1292 $this->isUserCssConfigPage()
1293 ||
$this->isUserJsonConfigPage()
1294 ||
$this->isUserJsConfigPage()
1299 * Trim down a .css, .json, or .js subpage title to get the corresponding skin name
1301 * @return string Containing skin name from .css, .json, or .js subpage title
1304 public function getSkinFromConfigSubpage() {
1305 $subpage = explode( '/', $this->mTextform
);
1306 $subpage = $subpage[count( $subpage ) - 1];
1307 $lastdot = strrpos( $subpage, '.' );
1308 if ( $lastdot === false ) {
1309 return $subpage; # Never happens: only called for names ending in '.css'/'.json'/'.js'
1311 return substr( $subpage, 0, $lastdot );
1315 * Is this a CSS "config" sub-page of a user page?
1320 public function isUserCssConfigPage() {
1322 NS_USER
== $this->mNamespace
1323 && $this->isSubpage()
1324 && $this->hasContentModel( CONTENT_MODEL_CSS
)
1329 * Is this a JSON "config" sub-page of a user page?
1334 public function isUserJsonConfigPage() {
1336 NS_USER
== $this->mNamespace
1337 && $this->isSubpage()
1338 && $this->hasContentModel( CONTENT_MODEL_JSON
)
1343 * Is this a JS "config" sub-page of a user page?
1348 public function isUserJsConfigPage() {
1350 NS_USER
== $this->mNamespace
1351 && $this->isSubpage()
1352 && $this->hasContentModel( CONTENT_MODEL_JAVASCRIPT
)
1357 * Is this a sitewide CSS "config" page?
1362 public function isSiteCssConfigPage() {
1364 NS_MEDIAWIKI
== $this->mNamespace
1366 $this->hasContentModel( CONTENT_MODEL_CSS
)
1367 // paranoia - a MediaWiki: namespace page with mismatching extension and content
1368 // model is probably by mistake and might get handled incorrectly (see e.g. T112937)
1369 ||
substr( $this->mDbkeyform
, -4 ) === '.css'
1375 * Is this a sitewide JSON "config" page?
1380 public function isSiteJsonConfigPage() {
1382 NS_MEDIAWIKI
== $this->mNamespace
1384 $this->hasContentModel( CONTENT_MODEL_JSON
)
1385 // paranoia - a MediaWiki: namespace page with mismatching extension and content
1386 // model is probably by mistake and might get handled incorrectly (see e.g. T112937)
1387 ||
substr( $this->mDbkeyform
, -5 ) === '.json'
1393 * Is this a sitewide JS "config" page?
1398 public function isSiteJsConfigPage() {
1400 NS_MEDIAWIKI
== $this->mNamespace
1402 $this->hasContentModel( CONTENT_MODEL_JAVASCRIPT
)
1403 // paranoia - a MediaWiki: namespace page with mismatching extension and content
1404 // model is probably by mistake and might get handled incorrectly (see e.g. T112937)
1405 ||
substr( $this->mDbkeyform
, -3 ) === '.js'
1411 * Is this a message which can contain raw HTML?
1416 public function isRawHtmlMessage() {
1417 global $wgRawHtmlMessages;
1419 if ( !$this->inNamespace( NS_MEDIAWIKI
) ) {
1422 $message = lcfirst( $this->getRootTitle()->getDBkey() );
1423 return in_array( $message, $wgRawHtmlMessages, true );
1427 * Is this a talk page of some sort?
1431 public function isTalkPage() {
1432 return MWNamespace
::isTalk( $this->mNamespace
);
1436 * Get a Title object associated with the talk page of this article
1438 * @return Title The object for the talk page
1440 public function getTalkPage() {
1441 return self
::makeTitle( MWNamespace
::getTalk( $this->mNamespace
), $this->mDbkeyform
);
1445 * Get a Title object associated with the talk page of this article,
1446 * if such a talk page can exist.
1450 * @return Title|null The object for the talk page,
1451 * or null if no associated talk page can exist, according to canHaveTalkPage().
1453 public function getTalkPageIfDefined() {
1454 if ( !$this->canHaveTalkPage() ) {
1458 return $this->getTalkPage();
1462 * Get a title object associated with the subject page of this
1465 * @return Title The object for the subject page
1467 public function getSubjectPage() {
1468 // Is this the same title?
1469 $subjectNS = MWNamespace
::getSubject( $this->mNamespace
);
1470 if ( $this->mNamespace
== $subjectNS ) {
1473 return self
::makeTitle( $subjectNS, $this->mDbkeyform
);
1477 * Get the other title for this page, if this is a subject page
1478 * get the talk page, if it is a subject page get the talk page
1481 * @throws MWException If the page doesn't have an other page
1484 public function getOtherPage() {
1485 if ( $this->isSpecialPage() ) {
1486 throw new MWException( 'Special pages cannot have other pages' );
1488 if ( $this->isTalkPage() ) {
1489 return $this->getSubjectPage();
1491 if ( !$this->canHaveTalkPage() ) {
1492 throw new MWException( "{$this->getPrefixedText()} does not have an other page" );
1494 return $this->getTalkPage();
1499 * Get the default namespace index, for when there is no namespace
1501 * @return int Default namespace index
1503 public function getDefaultNamespace() {
1504 return $this->mDefaultNamespace
;
1508 * Get the Title fragment (i.e.\ the bit after the #) in text form
1510 * Use Title::hasFragment to check for a fragment
1512 * @return string Title fragment
1514 public function getFragment() {
1515 return $this->mFragment
;
1519 * Check if a Title fragment is set
1524 public function hasFragment() {
1525 return $this->mFragment
!== '';
1529 * Get the fragment in URL form, including the "#" character if there is one
1531 * @return string Fragment in URL form
1533 public function getFragmentForURL() {
1534 if ( !$this->hasFragment() ) {
1536 } elseif ( $this->isExternal() ) {
1537 // Note: If the interwiki is unknown, it's treated as a namespace on the local wiki,
1538 // so we treat it like a local interwiki.
1539 $interwiki = self
::getInterwikiLookup()->fetch( $this->mInterwiki
);
1540 if ( $interwiki && !$interwiki->isLocal() ) {
1541 return '#' . Sanitizer
::escapeIdForExternalInterwiki( $this->mFragment
);
1545 return '#' . Sanitizer
::escapeIdForLink( $this->mFragment
);
1549 * Set the fragment for this title. Removes the first character from the
1550 * specified fragment before setting, so it assumes you're passing it with
1553 * Deprecated for public use, use Title::makeTitle() with fragment parameter,
1554 * or Title::createFragmentTarget().
1555 * Still in active use privately.
1558 * @param string $fragment Text
1560 public function setFragment( $fragment ) {
1561 $this->mFragment
= strtr( substr( $fragment, 1 ), '_', ' ' );
1565 * Creates a new Title for a different fragment of the same page.
1568 * @param string $fragment
1571 public function createFragmentTarget( $fragment ) {
1572 return self
::makeTitle(
1581 * Prefix some arbitrary text with the namespace or interwiki prefix
1584 * @param string $name The text
1585 * @return string The prefixed text
1587 private function prefix( $name ) {
1589 if ( $this->isExternal() ) {
1590 $p = $this->mInterwiki
. ':';
1593 if ( $this->mNamespace
!= 0 ) {
1594 $nsText = $this->getNsText();
1596 if ( $nsText === false ) {
1597 // See T165149. Awkward, but better than erroneously linking to the main namespace.
1598 $nsText = MediaWikiServices
::getInstance()->getContentLanguage()->
1599 getNsText( NS_SPECIAL
) . ":Badtitle/NS{$this->mNamespace}";
1602 $p .= $nsText . ':';
1608 * Get the prefixed database key form
1610 * @return string The prefixed title, with underscores and
1611 * any interwiki and namespace prefixes
1613 public function getPrefixedDBkey() {
1614 $s = $this->prefix( $this->mDbkeyform
);
1615 $s = strtr( $s, ' ', '_' );
1620 * Get the prefixed title with spaces.
1621 * This is the form usually used for display
1623 * @return string The prefixed title, with spaces
1625 public function getPrefixedText() {
1626 if ( $this->prefixedText
=== null ) {
1627 $s = $this->prefix( $this->mTextform
);
1628 $s = strtr( $s, '_', ' ' );
1629 $this->prefixedText
= $s;
1631 return $this->prefixedText
;
1635 * Return a string representation of this title
1637 * @return string Representation of this title
1639 public function __toString() {
1640 return $this->getPrefixedText();
1644 * Get the prefixed title with spaces, plus any fragment
1645 * (part beginning with '#')
1647 * @return string The prefixed title, with spaces and the fragment, including '#'
1649 public function getFullText() {
1650 $text = $this->getPrefixedText();
1651 if ( $this->hasFragment() ) {
1652 $text .= '#' . $this->mFragment
;
1658 * Get the root page name text without a namespace, i.e. the leftmost part before any slashes
1662 * Title::newFromText('User:Foo/Bar/Baz')->getRootText();
1666 * @return string Root name
1669 public function getRootText() {
1670 if ( !MWNamespace
::hasSubpages( $this->mNamespace
) ) {
1671 return $this->getText();
1674 return strtok( $this->getText(), '/' );
1678 * Get the root page name title, i.e. the leftmost part before any slashes
1682 * Title::newFromText('User:Foo/Bar/Baz')->getRootTitle();
1683 * # returns: Title{User:Foo}
1686 * @return Title Root title
1689 public function getRootTitle() {
1690 return self
::makeTitle( $this->mNamespace
, $this->getRootText() );
1694 * Get the base page name without a namespace, i.e. the part before the subpage name
1698 * Title::newFromText('User:Foo/Bar/Baz')->getBaseText();
1699 * # returns: 'Foo/Bar'
1702 * @return string Base name
1704 public function getBaseText() {
1705 if ( !MWNamespace
::hasSubpages( $this->mNamespace
) ) {
1706 return $this->getText();
1709 $parts = explode( '/', $this->getText() );
1710 # Don't discard the real title if there's no subpage involved
1711 if ( count( $parts ) > 1 ) {
1712 unset( $parts[count( $parts ) - 1] );
1714 return implode( '/', $parts );
1718 * Get the base page name title, i.e. the part before the subpage name
1722 * Title::newFromText('User:Foo/Bar/Baz')->getBaseTitle();
1723 * # returns: Title{User:Foo/Bar}
1726 * @return Title Base title
1729 public function getBaseTitle() {
1730 return self
::makeTitle( $this->mNamespace
, $this->getBaseText() );
1734 * Get the lowest-level subpage name, i.e. the rightmost part after any slashes
1738 * Title::newFromText('User:Foo/Bar/Baz')->getSubpageText();
1742 * @return string Subpage name
1744 public function getSubpageText() {
1745 if ( !MWNamespace
::hasSubpages( $this->mNamespace
) ) {
1746 return $this->mTextform
;
1748 $parts = explode( '/', $this->mTextform
);
1749 return $parts[count( $parts ) - 1];
1753 * Get the title for a subpage of the current page
1757 * Title::newFromText('User:Foo/Bar/Baz')->getSubpage("Asdf");
1758 * # returns: Title{User:Foo/Bar/Baz/Asdf}
1761 * @param string $text The subpage name to add to the title
1762 * @return Title|null Subpage title, or null on an error
1765 public function getSubpage( $text ) {
1766 return self
::makeTitleSafe( $this->mNamespace
, $this->getText() . '/' . $text );
1770 * Get a URL-encoded form of the subpage text
1772 * @return string URL-encoded subpage name
1774 public function getSubpageUrlForm() {
1775 $text = $this->getSubpageText();
1776 $text = wfUrlencode( strtr( $text, ' ', '_' ) );
1781 * Get a URL-encoded title (not an actual URL) including interwiki
1783 * @return string The URL-encoded form
1785 public function getPrefixedURL() {
1786 $s = $this->prefix( $this->mDbkeyform
);
1787 $s = wfUrlencode( strtr( $s, ' ', '_' ) );
1792 * Helper to fix up the get{Canonical,Full,Link,Local,Internal}URL args
1793 * get{Canonical,Full,Link,Local,Internal}URL methods accepted an optional
1794 * second argument named variant. This was deprecated in favor
1795 * of passing an array of option with a "variant" key
1796 * Once $query2 is removed for good, this helper can be dropped
1797 * and the wfArrayToCgi moved to getLocalURL();
1799 * @since 1.19 (r105919)
1800 * @param array|string $query
1801 * @param string|string[]|bool $query2
1804 private static function fixUrlQueryArgs( $query, $query2 = false ) {
1805 if ( $query2 !== false ) {
1806 wfDeprecated( "Title::get{Canonical,Full,Link,Local,Internal}URL " .
1807 "method called with a second parameter is deprecated. Add your " .
1808 "parameter to an array passed as the first parameter.", "1.19" );
1810 if ( is_array( $query ) ) {
1811 $query = wfArrayToCgi( $query );
1814 if ( is_string( $query2 ) ) {
1815 // $query2 is a string, we will consider this to be
1816 // a deprecated $variant argument and add it to the query
1817 $query2 = wfArrayToCgi( [ 'variant' => $query2 ] );
1819 $query2 = wfArrayToCgi( $query2 );
1821 // If we have $query content add a & to it first
1825 // Now append the queries together
1832 * Get a real URL referring to this title, with interwiki link and
1835 * @see self::getLocalURL for the arguments.
1837 * @param string|string[] $query
1838 * @param string|string[]|bool $query2
1839 * @param string|int|null $proto Protocol type to use in URL
1840 * @return string The URL
1842 public function getFullURL( $query = '', $query2 = false, $proto = PROTO_RELATIVE
) {
1843 $query = self
::fixUrlQueryArgs( $query, $query2 );
1845 # Hand off all the decisions on urls to getLocalURL
1846 $url = $this->getLocalURL( $query );
1848 # Expand the url to make it a full url. Note that getLocalURL has the
1849 # potential to output full urls for a variety of reasons, so we use
1850 # wfExpandUrl instead of simply prepending $wgServer
1851 $url = wfExpandUrl( $url, $proto );
1853 # Finally, add the fragment.
1854 $url .= $this->getFragmentForURL();
1855 // Avoid PHP 7.1 warning from passing $this by reference
1857 Hooks
::run( 'GetFullURL', [ &$titleRef, &$url, $query ] );
1862 * Get a url appropriate for making redirects based on an untrusted url arg
1864 * This is basically the same as getFullUrl(), but in the case of external
1865 * interwikis, we send the user to a landing page, to prevent possible
1866 * phishing attacks and the like.
1868 * @note Uses current protocol by default, since technically relative urls
1869 * aren't allowed in redirects per HTTP spec, so this is not suitable for
1870 * places where the url gets cached, as might pollute between
1871 * https and non-https users.
1872 * @see self::getLocalURL for the arguments.
1873 * @param array|string $query
1874 * @param string $proto Protocol type to use in URL
1875 * @return string A url suitable to use in an HTTP location header.
1877 public function getFullUrlForRedirect( $query = '', $proto = PROTO_CURRENT
) {
1879 if ( $this->isExternal() ) {
1880 $target = SpecialPage
::getTitleFor(
1882 $this->getPrefixedDBkey()
1885 return $target->getFullURL( $query, false, $proto );
1889 * Get a URL with no fragment or server name (relative URL) from a Title object.
1890 * If this page is generated with action=render, however,
1891 * $wgServer is prepended to make an absolute URL.
1893 * @see self::getFullURL to always get an absolute URL.
1894 * @see self::getLinkURL to always get a URL that's the simplest URL that will be
1895 * valid to link, locally, to the current Title.
1896 * @see self::newFromText to produce a Title object.
1898 * @param string|string[] $query An optional query string,
1899 * not used for interwiki links. Can be specified as an associative array as well,
1900 * e.g., array( 'action' => 'edit' ) (keys and values will be URL-escaped).
1901 * Some query patterns will trigger various shorturl path replacements.
1902 * @param string|string[]|bool $query2 An optional secondary query array. This one MUST
1903 * be an array. If a string is passed it will be interpreted as a deprecated
1904 * variant argument and urlencoded into a variant= argument.
1905 * This second query argument will be added to the $query
1906 * The second parameter is deprecated since 1.19. Pass it as a key,value
1907 * pair in the first parameter array instead.
1909 * @return string String of the URL.
1911 public function getLocalURL( $query = '', $query2 = false ) {
1912 global $wgArticlePath, $wgScript, $wgServer, $wgRequest;
1914 $query = self
::fixUrlQueryArgs( $query, $query2 );
1916 $interwiki = self
::getInterwikiLookup()->fetch( $this->mInterwiki
);
1918 $namespace = $this->getNsText();
1919 if ( $namespace != '' ) {
1920 # Can this actually happen? Interwikis shouldn't be parsed.
1921 # Yes! It can in interwiki transclusion. But... it probably shouldn't.
1924 $url = $interwiki->getURL( $namespace . $this->mDbkeyform
);
1925 $url = wfAppendQuery( $url, $query );
1927 $dbkey = wfUrlencode( $this->getPrefixedDBkey() );
1928 if ( $query == '' ) {
1929 $url = str_replace( '$1', $dbkey, $wgArticlePath );
1930 // Avoid PHP 7.1 warning from passing $this by reference
1932 Hooks
::run( 'GetLocalURL::Article', [ &$titleRef, &$url ] );
1934 global $wgVariantArticlePath, $wgActionPaths;
1938 if ( !empty( $wgActionPaths )
1939 && preg_match( '/^(.*&|)action=([^&]*)(&(.*)|)$/', $query, $matches )
1941 $action = urldecode( $matches[2] );
1942 if ( isset( $wgActionPaths[$action] ) ) {
1943 $query = $matches[1];
1944 if ( isset( $matches[4] ) ) {
1945 $query .= $matches[4];
1947 $url = str_replace( '$1', $dbkey, $wgActionPaths[$action] );
1948 if ( $query != '' ) {
1949 $url = wfAppendQuery( $url, $query );
1955 && $wgVariantArticlePath
1956 && preg_match( '/^variant=([^&]*)$/', $query, $matches )
1957 && $this->getPageLanguage()->equals(
1958 MediaWikiServices
::getInstance()->getContentLanguage() )
1959 && $this->getPageLanguage()->hasVariants()
1961 $variant = urldecode( $matches[1] );
1962 if ( $this->getPageLanguage()->hasVariant( $variant ) ) {
1963 // Only do the variant replacement if the given variant is a valid
1964 // variant for the page's language.
1965 $url = str_replace( '$2', urlencode( $variant ), $wgVariantArticlePath );
1966 $url = str_replace( '$1', $dbkey, $url );
1970 if ( $url === false ) {
1971 if ( $query == '-' ) {
1974 $url = "{$wgScript}?title={$dbkey}&{$query}";
1977 // Avoid PHP 7.1 warning from passing $this by reference
1979 Hooks
::run( 'GetLocalURL::Internal', [ &$titleRef, &$url, $query ] );
1981 // @todo FIXME: This causes breakage in various places when we
1982 // actually expected a local URL and end up with dupe prefixes.
1983 if ( $wgRequest->getVal( 'action' ) == 'render' ) {
1984 $url = $wgServer . $url;
1987 // Avoid PHP 7.1 warning from passing $this by reference
1989 Hooks
::run( 'GetLocalURL', [ &$titleRef, &$url, $query ] );
1994 * Get a URL that's the simplest URL that will be valid to link, locally,
1995 * to the current Title. It includes the fragment, but does not include
1996 * the server unless action=render is used (or the link is external). If
1997 * there's a fragment but the prefixed text is empty, we just return a link
2000 * The result obviously should not be URL-escaped, but does need to be
2001 * HTML-escaped if it's being output in HTML.
2003 * @param string|string[] $query
2004 * @param bool $query2
2005 * @param string|int|bool $proto A PROTO_* constant on how the URL should be expanded,
2006 * or false (default) for no expansion
2007 * @see self::getLocalURL for the arguments.
2008 * @return string The URL
2010 public function getLinkURL( $query = '', $query2 = false, $proto = false ) {
2011 if ( $this->isExternal() ||
$proto !== false ) {
2012 $ret = $this->getFullURL( $query, $query2, $proto );
2013 } elseif ( $this->getPrefixedText() === '' && $this->hasFragment() ) {
2014 $ret = $this->getFragmentForURL();
2016 $ret = $this->getLocalURL( $query, $query2 ) . $this->getFragmentForURL();
2022 * Get the URL form for an internal link.
2023 * - Used in various CDN-related code, in case we have a different
2024 * internal hostname for the server from the exposed one.
2026 * This uses $wgInternalServer to qualify the path, or $wgServer
2027 * if $wgInternalServer is not set. If the server variable used is
2028 * protocol-relative, the URL will be expanded to http://
2030 * @see self::getLocalURL for the arguments.
2031 * @param string $query
2032 * @param string|bool $query2
2033 * @return string The URL
2035 public function getInternalURL( $query = '', $query2 = false ) {
2036 global $wgInternalServer, $wgServer;
2037 $query = self
::fixUrlQueryArgs( $query, $query2 );
2038 $server = $wgInternalServer !== false ?
$wgInternalServer : $wgServer;
2039 $url = wfExpandUrl( $server . $this->getLocalURL( $query ), PROTO_HTTP
);
2040 // Avoid PHP 7.1 warning from passing $this by reference
2042 Hooks
::run( 'GetInternalURL', [ &$titleRef, &$url, $query ] );
2047 * Get the URL for a canonical link, for use in things like IRC and
2048 * e-mail notifications. Uses $wgCanonicalServer and the
2049 * GetCanonicalURL hook.
2051 * NOTE: Unlike getInternalURL(), the canonical URL includes the fragment
2053 * @see self::getLocalURL for the arguments.
2054 * @param string $query
2055 * @param string|bool $query2
2056 * @return string The URL
2059 public function getCanonicalURL( $query = '', $query2 = false ) {
2060 $query = self
::fixUrlQueryArgs( $query, $query2 );
2061 $url = wfExpandUrl( $this->getLocalURL( $query ) . $this->getFragmentForURL(), PROTO_CANONICAL
);
2062 // Avoid PHP 7.1 warning from passing $this by reference
2064 Hooks
::run( 'GetCanonicalURL', [ &$titleRef, &$url, $query ] );
2069 * Get the edit URL for this Title
2071 * @return string The URL, or a null string if this is an interwiki link
2073 public function getEditURL() {
2074 if ( $this->isExternal() ) {
2077 $s = $this->getLocalURL( 'action=edit' );
2083 * Can $user perform $action on this page?
2084 * This skips potentially expensive cascading permission checks
2085 * as well as avoids expensive error formatting
2087 * Suitable for use for nonessential UI controls in common cases, but
2088 * _not_ for functional access control.
2090 * May provide false positives, but should never provide a false negative.
2092 * @param string $action Action that permission needs to be checked for
2093 * @param User|null $user User to check (since 1.19); $wgUser will be used if not provided.
2096 public function quickUserCan( $action, $user = null ) {
2097 return $this->userCan( $action, $user, false );
2101 * Can $user perform $action on this page?
2103 * @param string $action Action that permission needs to be checked for
2104 * @param User|null $user User to check (since 1.19); $wgUser will be used if not
2106 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2109 public function userCan( $action, $user = null, $rigor = 'secure' ) {
2110 if ( !$user instanceof User
) {
2115 return !count( $this->getUserPermissionsErrorsInternal( $action, $user, $rigor, true ) );
2119 * Can $user perform $action on this page?
2121 * @todo FIXME: This *does not* check throttles (User::pingLimiter()).
2123 * @param string $action Action that permission needs to be checked for
2124 * @param User $user User to check
2125 * @param string $rigor One of (quick,full,secure)
2126 * - quick : does cheap permission checks from replica DBs (usable for GUI creation)
2127 * - full : does cheap and expensive checks possibly from a replica DB
2128 * - secure : does cheap and expensive checks, using the master as needed
2129 * @param array $ignoreErrors Array of Strings Set this to a list of message keys
2130 * whose corresponding errors may be ignored.
2131 * @return array Array of arrays of the arguments to wfMessage to explain permissions problems.
2133 public function getUserPermissionsErrors(
2134 $action, $user, $rigor = 'secure', $ignoreErrors = []
2136 $errors = $this->getUserPermissionsErrorsInternal( $action, $user, $rigor );
2138 // Remove the errors being ignored.
2139 foreach ( $errors as $index => $error ) {
2140 $errKey = is_array( $error ) ?
$error[0] : $error;
2142 if ( in_array( $errKey, $ignoreErrors ) ) {
2143 unset( $errors[$index] );
2145 if ( $errKey instanceof MessageSpecifier
&& in_array( $errKey->getKey(), $ignoreErrors ) ) {
2146 unset( $errors[$index] );
2154 * Permissions checks that fail most often, and which are easiest to test.
2156 * @param string $action The action to check
2157 * @param User $user User to check
2158 * @param array $errors List of current errors
2159 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2160 * @param bool $short Short circuit on first error
2162 * @return array List of errors
2164 private function checkQuickPermissions( $action, $user, $errors, $rigor, $short ) {
2165 if ( !Hooks
::run( 'TitleQuickPermissions',
2166 [ $this, $user, $action, &$errors, ( $rigor !== 'quick' ), $short ] )
2171 if ( $action == 'create' ) {
2173 ( $this->isTalkPage() && !$user->isAllowed( 'createtalk' ) ) ||
2174 ( !$this->isTalkPage() && !$user->isAllowed( 'createpage' ) )
2176 $errors[] = $user->isAnon() ?
[ 'nocreatetext' ] : [ 'nocreate-loggedin' ];
2178 } elseif ( $action == 'move' ) {
2179 if ( !$user->isAllowed( 'move-rootuserpages' )
2180 && $this->mNamespace
== NS_USER
&& !$this->isSubpage() ) {
2181 // Show user page-specific message only if the user can move other pages
2182 $errors[] = [ 'cant-move-user-page' ];
2185 // Check if user is allowed to move files if it's a file
2186 if ( $this->mNamespace
== NS_FILE
&& !$user->isAllowed( 'movefile' ) ) {
2187 $errors[] = [ 'movenotallowedfile' ];
2190 // Check if user is allowed to move category pages if it's a category page
2191 if ( $this->mNamespace
== NS_CATEGORY
&& !$user->isAllowed( 'move-categorypages' ) ) {
2192 $errors[] = [ 'cant-move-category-page' ];
2195 if ( !$user->isAllowed( 'move' ) ) {
2196 // User can't move anything
2197 $userCanMove = User
::groupHasPermission( 'user', 'move' );
2198 $autoconfirmedCanMove = User
::groupHasPermission( 'autoconfirmed', 'move' );
2199 if ( $user->isAnon() && ( $userCanMove ||
$autoconfirmedCanMove ) ) {
2200 // custom message if logged-in users without any special rights can move
2201 $errors[] = [ 'movenologintext' ];
2203 $errors[] = [ 'movenotallowed' ];
2206 } elseif ( $action == 'move-target' ) {
2207 if ( !$user->isAllowed( 'move' ) ) {
2208 // User can't move anything
2209 $errors[] = [ 'movenotallowed' ];
2210 } elseif ( !$user->isAllowed( 'move-rootuserpages' )
2211 && $this->mNamespace
== NS_USER
&& !$this->isSubpage() ) {
2212 // Show user page-specific message only if the user can move other pages
2213 $errors[] = [ 'cant-move-to-user-page' ];
2214 } elseif ( !$user->isAllowed( 'move-categorypages' )
2215 && $this->mNamespace
== NS_CATEGORY
) {
2216 // Show category page-specific message only if the user can move other pages
2217 $errors[] = [ 'cant-move-to-category-page' ];
2219 } elseif ( !$user->isAllowed( $action ) ) {
2220 $errors[] = $this->missingPermissionError( $action, $short );
2227 * Add the resulting error code to the errors array
2229 * @param array $errors List of current errors
2230 * @param array $result Result of errors
2232 * @return array List of errors
2234 private function resultToError( $errors, $result ) {
2235 if ( is_array( $result ) && count( $result ) && !is_array( $result[0] ) ) {
2236 // A single array representing an error
2237 $errors[] = $result;
2238 } elseif ( is_array( $result ) && is_array( $result[0] ) ) {
2239 // A nested array representing multiple errors
2240 $errors = array_merge( $errors, $result );
2241 } elseif ( $result !== '' && is_string( $result ) ) {
2242 // A string representing a message-id
2243 $errors[] = [ $result ];
2244 } elseif ( $result instanceof MessageSpecifier
) {
2245 // A message specifier representing an error
2246 $errors[] = [ $result ];
2247 } elseif ( $result === false ) {
2248 // a generic "We don't want them to do that"
2249 $errors[] = [ 'badaccess-group0' ];
2255 * Check various permission hooks
2257 * @param string $action The action to check
2258 * @param User $user User to check
2259 * @param array $errors List of current errors
2260 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2261 * @param bool $short Short circuit on first error
2263 * @return array List of errors
2265 private function checkPermissionHooks( $action, $user, $errors, $rigor, $short ) {
2266 // Use getUserPermissionsErrors instead
2268 // Avoid PHP 7.1 warning from passing $this by reference
2270 if ( !Hooks
::run( 'userCan', [ &$titleRef, &$user, $action, &$result ] ) ) {
2271 return $result ?
[] : [ [ 'badaccess-group0' ] ];
2273 // Check getUserPermissionsErrors hook
2274 // Avoid PHP 7.1 warning from passing $this by reference
2276 if ( !Hooks
::run( 'getUserPermissionsErrors', [ &$titleRef, &$user, $action, &$result ] ) ) {
2277 $errors = $this->resultToError( $errors, $result );
2279 // Check getUserPermissionsErrorsExpensive hook
2282 && !( $short && count( $errors ) > 0 )
2283 && !Hooks
::run( 'getUserPermissionsErrorsExpensive', [ &$titleRef, &$user, $action, &$result ] )
2285 $errors = $this->resultToError( $errors, $result );
2292 * Check permissions on special pages & namespaces
2294 * @param string $action The action to check
2295 * @param User $user User to check
2296 * @param array $errors List of current errors
2297 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2298 * @param bool $short Short circuit on first error
2300 * @return array List of errors
2302 private function checkSpecialsAndNSPermissions( $action, $user, $errors, $rigor, $short ) {
2303 # Only 'createaccount' can be performed on special pages,
2304 # which don't actually exist in the DB.
2305 if ( $this->isSpecialPage() && $action !== 'createaccount' ) {
2306 $errors[] = [ 'ns-specialprotected' ];
2309 # Check $wgNamespaceProtection for restricted namespaces
2310 if ( $this->isNamespaceProtected( $user ) ) {
2311 $ns = $this->mNamespace
== NS_MAIN ?
2312 wfMessage( 'nstab-main' )->text() : $this->getNsText();
2313 $errors[] = $this->mNamespace
== NS_MEDIAWIKI ?
2314 [ 'protectedinterface', $action ] : [ 'namespaceprotected', $ns, $action ];
2321 * Check sitewide CSS/JSON/JS permissions
2323 * @param string $action The action to check
2324 * @param User $user User to check
2325 * @param array $errors List of current errors
2326 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2327 * @param bool $short Short circuit on first error
2329 * @return array List of errors
2331 private function checkSiteConfigPermissions( $action, $user, $errors, $rigor, $short ) {
2332 if ( $action != 'patrol' ) {
2334 // Sitewide CSS/JSON/JS changes, like all NS_MEDIAWIKI changes, also require the
2335 // editinterface right. That's implemented as a restriction so no check needed here.
2336 if ( $this->isSiteCssConfigPage() && !$user->isAllowed( 'editsitecss' ) ) {
2337 $error = [ 'sitecssprotected', $action ];
2338 } elseif ( $this->isSiteJsonConfigPage() && !$user->isAllowed( 'editsitejson' ) ) {
2339 $error = [ 'sitejsonprotected', $action ];
2340 } elseif ( $this->isSiteJsConfigPage() && !$user->isAllowed( 'editsitejs' ) ) {
2341 $error = [ 'sitejsprotected', $action ];
2342 } elseif ( $this->isRawHtmlMessage() ) {
2343 // Raw HTML can be used to deploy CSS or JS so require rights for both.
2344 if ( !$user->isAllowed( 'editsitejs' ) ) {
2345 $error = [ 'sitejsprotected', $action ];
2346 } elseif ( !$user->isAllowed( 'editsitecss' ) ) {
2347 $error = [ 'sitecssprotected', $action ];
2352 if ( $user->isAllowed( 'editinterface' ) ) {
2353 // Most users / site admins will probably find out about the new, more restrictive
2354 // permissions by failing to edit something. Give them more info.
2355 // TODO remove this a few release cycles after 1.32
2356 $error = [ 'interfaceadmin-info', wfMessage( $error[0], $error[1] ) ];
2366 * Check CSS/JSON/JS sub-page permissions
2368 * @param string $action The action to check
2369 * @param User $user User to check
2370 * @param array $errors List of current errors
2371 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2372 * @param bool $short Short circuit on first error
2374 * @return array List of errors
2376 private function checkUserConfigPermissions( $action, $user, $errors, $rigor, $short ) {
2377 # Protect css/json/js subpages of user pages
2378 # XXX: this might be better using restrictions
2380 if ( $action === 'patrol' ) {
2384 if ( preg_match( '/^' . preg_quote( $user->getName(), '/' ) . '\//', $this->mTextform
) ) {
2385 // Users need editmyuser* to edit their own CSS/JSON/JS subpages.
2387 $this->isUserCssConfigPage()
2388 && !$user->isAllowedAny( 'editmyusercss', 'editusercss' )
2390 $errors[] = [ 'mycustomcssprotected', $action ];
2392 $this->isUserJsonConfigPage()
2393 && !$user->isAllowedAny( 'editmyuserjson', 'edituserjson' )
2395 $errors[] = [ 'mycustomjsonprotected', $action ];
2397 $this->isUserJsConfigPage()
2398 && !$user->isAllowedAny( 'editmyuserjs', 'edituserjs' )
2400 $errors[] = [ 'mycustomjsprotected', $action ];
2403 // Users need editmyuser* to edit their own CSS/JSON/JS subpages, except for
2404 // deletion/suppression which cannot be used for attacks and we want to avoid the
2405 // situation where an unprivileged user can post abusive content on their subpages
2406 // and only very highly privileged users could remove it.
2407 if ( !in_array( $action, [ 'delete', 'deleterevision', 'suppressrevision' ], true ) ) {
2409 $this->isUserCssConfigPage()
2410 && !$user->isAllowed( 'editusercss' )
2412 $errors[] = [ 'customcssprotected', $action ];
2414 $this->isUserJsonConfigPage()
2415 && !$user->isAllowed( 'edituserjson' )
2417 $errors[] = [ 'customjsonprotected', $action ];
2419 $this->isUserJsConfigPage()
2420 && !$user->isAllowed( 'edituserjs' )
2422 $errors[] = [ 'customjsprotected', $action ];
2431 * Check against page_restrictions table requirements on this
2432 * page. The user must possess all required rights for this
2435 * @param string $action The action to check
2436 * @param User $user User to check
2437 * @param array $errors List of current errors
2438 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2439 * @param bool $short Short circuit on first error
2441 * @return array List of errors
2443 private function checkPageRestrictions( $action, $user, $errors, $rigor, $short ) {
2444 foreach ( $this->getRestrictions( $action ) as $right ) {
2445 // Backwards compatibility, rewrite sysop -> editprotected
2446 if ( $right == 'sysop' ) {
2447 $right = 'editprotected';
2449 // Backwards compatibility, rewrite autoconfirmed -> editsemiprotected
2450 if ( $right == 'autoconfirmed' ) {
2451 $right = 'editsemiprotected';
2453 if ( $right == '' ) {
2456 if ( !$user->isAllowed( $right ) ) {
2457 $errors[] = [ 'protectedpagetext', $right, $action ];
2458 } elseif ( $this->mCascadeRestriction
&& !$user->isAllowed( 'protect' ) ) {
2459 $errors[] = [ 'protectedpagetext', 'protect', $action ];
2467 * Check restrictions on cascading pages.
2469 * @param string $action The action to check
2470 * @param User $user User to check
2471 * @param array $errors List of current errors
2472 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2473 * @param bool $short Short circuit on first error
2475 * @return array List of errors
2477 private function checkCascadingSourcesRestrictions( $action, $user, $errors, $rigor, $short ) {
2478 if ( $rigor !== 'quick' && !$this->isUserConfigPage() ) {
2479 # We /could/ use the protection level on the source page, but it's
2480 # fairly ugly as we have to establish a precedence hierarchy for pages
2481 # included by multiple cascade-protected pages. So just restrict
2482 # it to people with 'protect' permission, as they could remove the
2483 # protection anyway.
2484 list( $cascadingSources, $restrictions ) = $this->getCascadeProtectionSources();
2485 # Cascading protection depends on more than this page...
2486 # Several cascading protected pages may include this page...
2487 # Check each cascading level
2488 # This is only for protection restrictions, not for all actions
2489 if ( isset( $restrictions[$action] ) ) {
2490 foreach ( $restrictions[$action] as $right ) {
2491 // Backwards compatibility, rewrite sysop -> editprotected
2492 if ( $right == 'sysop' ) {
2493 $right = 'editprotected';
2495 // Backwards compatibility, rewrite autoconfirmed -> editsemiprotected
2496 if ( $right == 'autoconfirmed' ) {
2497 $right = 'editsemiprotected';
2499 if ( $right != '' && !$user->isAllowedAll( 'protect', $right ) ) {
2501 foreach ( $cascadingSources as $page ) {
2502 $pages .= '* [[:' . $page->getPrefixedText() . "]]\n";
2504 $errors[] = [ 'cascadeprotected', count( $cascadingSources ), $pages, $action ];
2514 * Check action permissions not already checked in checkQuickPermissions
2516 * @param string $action The action to check
2517 * @param User $user User to check
2518 * @param array $errors List of current errors
2519 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2520 * @param bool $short Short circuit on first error
2522 * @return array List of errors
2524 private function checkActionPermissions( $action, $user, $errors, $rigor, $short ) {
2525 global $wgDeleteRevisionsLimit, $wgLang;
2527 if ( $action == 'protect' ) {
2528 if ( count( $this->getUserPermissionsErrorsInternal( 'edit', $user, $rigor, true ) ) ) {
2529 // If they can't edit, they shouldn't protect.
2530 $errors[] = [ 'protect-cantedit' ];
2532 } elseif ( $action == 'create' ) {
2533 $title_protection = $this->getTitleProtection();
2534 if ( $title_protection ) {
2535 if ( $title_protection['permission'] == ''
2536 ||
!$user->isAllowed( $title_protection['permission'] )
2540 User
::whoIs( $title_protection['user'] ),
2541 $title_protection['reason']
2545 } elseif ( $action == 'move' ) {
2546 // Check for immobile pages
2547 if ( !MWNamespace
::isMovable( $this->mNamespace
) ) {
2548 // Specific message for this case
2549 $errors[] = [ 'immobile-source-namespace', $this->getNsText() ];
2550 } elseif ( !$this->isMovable() ) {
2551 // Less specific message for rarer cases
2552 $errors[] = [ 'immobile-source-page' ];
2554 } elseif ( $action == 'move-target' ) {
2555 if ( !MWNamespace
::isMovable( $this->mNamespace
) ) {
2556 $errors[] = [ 'immobile-target-namespace', $this->getNsText() ];
2557 } elseif ( !$this->isMovable() ) {
2558 $errors[] = [ 'immobile-target-page' ];
2560 } elseif ( $action == 'delete' ) {
2561 $tempErrors = $this->checkPageRestrictions( 'edit', $user, [], $rigor, true );
2562 if ( !$tempErrors ) {
2563 $tempErrors = $this->checkCascadingSourcesRestrictions( 'edit',
2564 $user, $tempErrors, $rigor, true );
2566 if ( $tempErrors ) {
2567 // If protection keeps them from editing, they shouldn't be able to delete.
2568 $errors[] = [ 'deleteprotected' ];
2570 if ( $rigor !== 'quick' && $wgDeleteRevisionsLimit
2571 && !$this->userCan( 'bigdelete', $user ) && $this->isBigDeletion()
2573 $errors[] = [ 'delete-toobig', $wgLang->formatNum( $wgDeleteRevisionsLimit ) ];
2575 } elseif ( $action === 'undelete' ) {
2576 if ( count( $this->getUserPermissionsErrorsInternal( 'edit', $user, $rigor, true ) ) ) {
2577 // Undeleting implies editing
2578 $errors[] = [ 'undelete-cantedit' ];
2580 if ( !$this->exists()
2581 && count( $this->getUserPermissionsErrorsInternal( 'create', $user, $rigor, true ) )
2583 // Undeleting where nothing currently exists implies creating
2584 $errors[] = [ 'undelete-cantcreate' ];
2591 * Check that the user isn't blocked from editing.
2593 * @param string $action The action to check
2594 * @param User $user User to check
2595 * @param array $errors List of current errors
2596 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2597 * @param bool $short Short circuit on first error
2599 * @return array List of errors
2601 private function checkUserBlock( $action, $user, $errors, $rigor, $short ) {
2602 global $wgEmailConfirmToEdit, $wgBlockDisablesLogin;
2603 // Account creation blocks handled at userlogin.
2604 // Unblocking handled in SpecialUnblock
2605 if ( $rigor === 'quick' ||
in_array( $action, [ 'createaccount', 'unblock' ] ) ) {
2609 // Optimize for a very common case
2610 if ( $action === 'read' && !$wgBlockDisablesLogin ) {
2614 if ( $wgEmailConfirmToEdit
2615 && !$user->isEmailConfirmed()
2616 && $action === 'edit'
2618 $errors[] = [ 'confirmedittext' ];
2621 $useReplica = ( $rigor !== 'secure' );
2622 $block = $user->getBlock( $useReplica );
2624 // If the user does not have a block, or the block they do have explicitly
2625 // allows the action (like "read" or "upload").
2626 if ( !$block ||
$block->appliesToRight( $action ) === false ) {
2630 // Determine if the user is blocked from this action on this page.
2631 // What gets passed into this method is a user right, not an action name.
2632 // There is no way to instantiate an action by restriction. However, this
2633 // will get the action where the restriction is the same. This may result
2634 // in actions being blocked that shouldn't be.
2636 if ( Action
::exists( $action ) ) {
2637 // Clone the title to prevent mutations to this object which is done
2638 // by Title::loadFromRow() in WikiPage::loadFromRow().
2639 $page = WikiPage
::factory( clone $this );
2640 // Creating an action will perform several database queries to ensure that
2641 // the action has not been overridden by the content type.
2642 // @todo FIXME: Pass the relevant context into this function.
2643 $actionObj = Action
::factory( $action, $page, RequestContext
::getMain() );
2644 // Ensure that the retrieved action matches the restriction.
2645 if ( $actionObj && $actionObj->getRestriction() !== $action ) {
2650 // If no action object is returned, assume that the action requires unblock
2651 // which is the default.
2652 if ( !$actionObj ||
$actionObj->requiresUnblock() ) {
2653 if ( $user->isBlockedFrom( $this, $useReplica ) ) {
2654 // @todo FIXME: Pass the relevant context into this function.
2655 $errors[] = $block->getPermissionsError( RequestContext
::getMain() );
2663 * Check that the user is allowed to read this page.
2665 * @param string $action The action to check
2666 * @param User $user User to check
2667 * @param array $errors List of current errors
2668 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2669 * @param bool $short Short circuit on first error
2671 * @return array List of errors
2673 private function checkReadPermissions( $action, $user, $errors, $rigor, $short ) {
2674 global $wgWhitelistRead, $wgWhitelistReadRegexp;
2676 $whitelisted = false;
2677 if ( User
::isEveryoneAllowed( 'read' ) ) {
2678 # Shortcut for public wikis, allows skipping quite a bit of code
2679 $whitelisted = true;
2680 } elseif ( $user->isAllowed( 'read' ) ) {
2681 # If the user is allowed to read pages, he is allowed to read all pages
2682 $whitelisted = true;
2683 } elseif ( $this->isSpecial( 'Userlogin' )
2684 ||
$this->isSpecial( 'PasswordReset' )
2685 ||
$this->isSpecial( 'Userlogout' )
2687 # Always grant access to the login page.
2688 # Even anons need to be able to log in.
2689 $whitelisted = true;
2690 } elseif ( is_array( $wgWhitelistRead ) && count( $wgWhitelistRead ) ) {
2691 # Time to check the whitelist
2692 # Only do these checks is there's something to check against
2693 $name = $this->getPrefixedText();
2694 $dbName = $this->getPrefixedDBkey();
2696 // Check for explicit whitelisting with and without underscores
2697 if ( in_array( $name, $wgWhitelistRead, true ) ||
in_array( $dbName, $wgWhitelistRead, true ) ) {
2698 $whitelisted = true;
2699 } elseif ( $this->mNamespace
== NS_MAIN
) {
2700 # Old settings might have the title prefixed with
2701 # a colon for main-namespace pages
2702 if ( in_array( ':' . $name, $wgWhitelistRead ) ) {
2703 $whitelisted = true;
2705 } elseif ( $this->isSpecialPage() ) {
2706 # If it's a special page, ditch the subpage bit and check again
2707 $name = $this->mDbkeyform
;
2708 list( $name, /* $subpage */ ) =
2709 MediaWikiServices
::getInstance()->getSpecialPageFactory()->
2710 resolveAlias( $name );
2712 $pure = SpecialPage
::getTitleFor( $name )->getPrefixedText();
2713 if ( in_array( $pure, $wgWhitelistRead, true ) ) {
2714 $whitelisted = true;
2720 if ( !$whitelisted && is_array( $wgWhitelistReadRegexp ) && !empty( $wgWhitelistReadRegexp ) ) {
2721 $name = $this->getPrefixedText();
2722 // Check for regex whitelisting
2723 foreach ( $wgWhitelistReadRegexp as $listItem ) {
2724 if ( preg_match( $listItem, $name ) ) {
2725 $whitelisted = true;
2731 if ( !$whitelisted ) {
2732 # If the title is not whitelisted, give extensions a chance to do so...
2733 Hooks
::run( 'TitleReadWhitelist', [ $this, $user, &$whitelisted ] );
2734 if ( !$whitelisted ) {
2735 $errors[] = $this->missingPermissionError( $action, $short );
2743 * Get a description array when the user doesn't have the right to perform
2744 * $action (i.e. when User::isAllowed() returns false)
2746 * @param string $action The action to check
2747 * @param bool $short Short circuit on first error
2748 * @return array Array containing an error message key and any parameters
2750 private function missingPermissionError( $action, $short ) {
2751 // We avoid expensive display logic for quickUserCan's and such
2753 return [ 'badaccess-group0' ];
2756 return User
::newFatalPermissionDeniedStatus( $action )->getErrorsArray()[0];
2760 * Can $user perform $action on this page? This is an internal function,
2761 * with multiple levels of checks depending on performance needs; see $rigor below.
2762 * It does not check wfReadOnly().
2764 * @param string $action Action that permission needs to be checked for
2765 * @param User $user User to check
2766 * @param string $rigor One of (quick,full,secure)
2767 * - quick : does cheap permission checks from replica DBs (usable for GUI creation)
2768 * - full : does cheap and expensive checks possibly from a replica DB
2769 * - secure : does cheap and expensive checks, using the master as needed
2770 * @param bool $short Set this to true to stop after the first permission error.
2771 * @return array Array of arrays of the arguments to wfMessage to explain permissions problems.
2773 protected function getUserPermissionsErrorsInternal(
2774 $action, $user, $rigor = 'secure', $short = false
2776 if ( $rigor === true ) {
2777 $rigor = 'secure'; // b/c
2778 } elseif ( $rigor === false ) {
2779 $rigor = 'quick'; // b/c
2780 } elseif ( !in_array( $rigor, [ 'quick', 'full', 'secure' ] ) ) {
2781 throw new Exception( "Invalid rigor parameter '$rigor'." );
2784 # Read has special handling
2785 if ( $action == 'read' ) {
2787 'checkPermissionHooks',
2788 'checkReadPermissions',
2789 'checkUserBlock', // for wgBlockDisablesLogin
2791 # Don't call checkSpecialsAndNSPermissions, checkSiteConfigPermissions
2792 # or checkUserConfigPermissions here as it will lead to duplicate
2793 # error messages. This is okay to do since anywhere that checks for
2794 # create will also check for edit, and those checks are called for edit.
2795 } elseif ( $action == 'create' ) {
2797 'checkQuickPermissions',
2798 'checkPermissionHooks',
2799 'checkPageRestrictions',
2800 'checkCascadingSourcesRestrictions',
2801 'checkActionPermissions',
2806 'checkQuickPermissions',
2807 'checkPermissionHooks',
2808 'checkSpecialsAndNSPermissions',
2809 'checkSiteConfigPermissions',
2810 'checkUserConfigPermissions',
2811 'checkPageRestrictions',
2812 'checkCascadingSourcesRestrictions',
2813 'checkActionPermissions',
2819 foreach ( $checks as $method ) {
2820 $errors = $this->$method( $action, $user, $errors, $rigor, $short );
2822 if ( $short && $errors !== [] ) {
2831 * Get a filtered list of all restriction types supported by this wiki.
2832 * @param bool $exists True to get all restriction types that apply to
2833 * titles that do exist, False for all restriction types that apply to
2834 * titles that do not exist
2837 public static function getFilteredRestrictionTypes( $exists = true ) {
2838 global $wgRestrictionTypes;
2839 $types = $wgRestrictionTypes;
2841 # Remove the create restriction for existing titles
2842 $types = array_diff( $types, [ 'create' ] );
2844 # Only the create and upload restrictions apply to non-existing titles
2845 $types = array_intersect( $types, [ 'create', 'upload' ] );
2851 * Returns restriction types for the current Title
2853 * @return array Applicable restriction types
2855 public function getRestrictionTypes() {
2856 if ( $this->isSpecialPage() ) {
2860 $types = self
::getFilteredRestrictionTypes( $this->exists() );
2862 if ( $this->mNamespace
!= NS_FILE
) {
2863 # Remove the upload restriction for non-file titles
2864 $types = array_diff( $types, [ 'upload' ] );
2867 Hooks
::run( 'TitleGetRestrictionTypes', [ $this, &$types ] );
2869 wfDebug( __METHOD__
. ': applicable restrictions to [[' .
2870 $this->getPrefixedText() . ']] are {' . implode( ',', $types ) . "}\n" );
2876 * Is this title subject to title protection?
2877 * Title protection is the one applied against creation of such title.
2879 * @return array|bool An associative array representing any existent title
2880 * protection, or false if there's none.
2882 public function getTitleProtection() {
2883 $protection = $this->getTitleProtectionInternal();
2884 if ( $protection ) {
2885 if ( $protection['permission'] == 'sysop' ) {
2886 $protection['permission'] = 'editprotected'; // B/C
2888 if ( $protection['permission'] == 'autoconfirmed' ) {
2889 $protection['permission'] = 'editsemiprotected'; // B/C
2896 * Fetch title protection settings
2898 * To work correctly, $this->loadRestrictions() needs to have access to the
2899 * actual protections in the database without munging 'sysop' =>
2900 * 'editprotected' and 'autoconfirmed' => 'editsemiprotected'. Other
2901 * callers probably want $this->getTitleProtection() instead.
2903 * @return array|bool
2905 protected function getTitleProtectionInternal() {
2906 // Can't protect pages in special namespaces
2907 if ( $this->mNamespace
< 0 ) {
2911 // Can't protect pages that exist.
2912 if ( $this->exists() ) {
2916 if ( $this->mTitleProtection
=== null ) {
2917 $dbr = wfGetDB( DB_REPLICA
);
2918 $commentStore = CommentStore
::getStore();
2919 $commentQuery = $commentStore->getJoin( 'pt_reason' );
2920 $res = $dbr->select(
2921 [ 'protected_titles' ] +
$commentQuery['tables'],
2923 'user' => 'pt_user',
2924 'expiry' => 'pt_expiry',
2925 'permission' => 'pt_create_perm'
2926 ] +
$commentQuery['fields'],
2927 [ 'pt_namespace' => $this->mNamespace
, 'pt_title' => $this->mDbkeyform
],
2930 $commentQuery['joins']
2933 // fetchRow returns false if there are no rows.
2934 $row = $dbr->fetchRow( $res );
2936 $this->mTitleProtection
= [
2937 'user' => $row['user'],
2938 'expiry' => $dbr->decodeExpiry( $row['expiry'] ),
2939 'permission' => $row['permission'],
2940 'reason' => $commentStore->getComment( 'pt_reason', $row )->text
,
2943 $this->mTitleProtection
= false;
2946 return $this->mTitleProtection
;
2950 * Remove any title protection due to page existing
2952 public function deleteTitleProtection() {
2953 $dbw = wfGetDB( DB_MASTER
);
2957 [ 'pt_namespace' => $this->mNamespace
, 'pt_title' => $this->mDbkeyform
],
2960 $this->mTitleProtection
= false;
2964 * Is this page "semi-protected" - the *only* protection levels are listed
2965 * in $wgSemiprotectedRestrictionLevels?
2967 * @param string $action Action to check (default: edit)
2970 public function isSemiProtected( $action = 'edit' ) {
2971 global $wgSemiprotectedRestrictionLevels;
2973 $restrictions = $this->getRestrictions( $action );
2974 $semi = $wgSemiprotectedRestrictionLevels;
2975 if ( !$restrictions ||
!$semi ) {
2976 // Not protected, or all protection is full protection
2980 // Remap autoconfirmed to editsemiprotected for BC
2981 foreach ( array_keys( $semi, 'autoconfirmed' ) as $key ) {
2982 $semi[$key] = 'editsemiprotected';
2984 foreach ( array_keys( $restrictions, 'autoconfirmed' ) as $key ) {
2985 $restrictions[$key] = 'editsemiprotected';
2988 return !array_diff( $restrictions, $semi );
2992 * Does the title correspond to a protected article?
2994 * @param string $action The action the page is protected from,
2995 * by default checks all actions.
2998 public function isProtected( $action = '' ) {
2999 global $wgRestrictionLevels;
3001 $restrictionTypes = $this->getRestrictionTypes();
3003 # Special pages have inherent protection
3004 if ( $this->isSpecialPage() ) {
3008 # Check regular protection levels
3009 foreach ( $restrictionTypes as $type ) {
3010 if ( $action == $type ||
$action == '' ) {
3011 $r = $this->getRestrictions( $type );
3012 foreach ( $wgRestrictionLevels as $level ) {
3013 if ( in_array( $level, $r ) && $level != '' ) {
3024 * Determines if $user is unable to edit this page because it has been protected
3025 * by $wgNamespaceProtection.
3027 * @param User $user User object to check permissions
3030 public function isNamespaceProtected( User
$user ) {
3031 global $wgNamespaceProtection;
3033 if ( isset( $wgNamespaceProtection[$this->mNamespace
] ) ) {
3034 foreach ( (array)$wgNamespaceProtection[$this->mNamespace
] as $right ) {
3035 if ( $right != '' && !$user->isAllowed( $right ) ) {
3044 * Cascading protection: Return true if cascading restrictions apply to this page, false if not.
3046 * @return bool If the page is subject to cascading restrictions.
3048 public function isCascadeProtected() {
3049 list( $sources, /* $restrictions */ ) = $this->getCascadeProtectionSources( false );
3050 return ( $sources > 0 );
3054 * Determines whether cascading protection sources have already been loaded from
3057 * @param bool $getPages True to check if the pages are loaded, or false to check
3058 * if the status is loaded.
3059 * @return bool Whether or not the specified information has been loaded
3062 public function areCascadeProtectionSourcesLoaded( $getPages = true ) {
3063 return $getPages ?
$this->mCascadeSources
!== null : $this->mHasCascadingRestrictions
!== null;
3067 * Cascading protection: Get the source of any cascading restrictions on this page.
3069 * @param bool $getPages Whether or not to retrieve the actual pages
3070 * that the restrictions have come from and the actual restrictions
3072 * @return array Two elements: First is an array of Title objects of the
3073 * pages from which cascading restrictions have come, false for
3074 * none, or true if such restrictions exist but $getPages was not
3075 * set. Second is an array like that returned by
3076 * Title::getAllRestrictions(), or an empty array if $getPages is
3079 public function getCascadeProtectionSources( $getPages = true ) {
3080 $pagerestrictions = [];
3082 if ( $this->mCascadeSources
!== null && $getPages ) {
3083 return [ $this->mCascadeSources
, $this->mCascadingRestrictions
];
3084 } elseif ( $this->mHasCascadingRestrictions
!== null && !$getPages ) {
3085 return [ $this->mHasCascadingRestrictions
, $pagerestrictions ];
3088 $dbr = wfGetDB( DB_REPLICA
);
3090 if ( $this->mNamespace
== NS_FILE
) {
3091 $tables = [ 'imagelinks', 'page_restrictions' ];
3093 'il_to' => $this->mDbkeyform
,
3098 $tables = [ 'templatelinks', 'page_restrictions' ];
3100 'tl_namespace' => $this->mNamespace
,
3101 'tl_title' => $this->mDbkeyform
,
3108 $cols = [ 'pr_page', 'page_namespace', 'page_title',
3109 'pr_expiry', 'pr_type', 'pr_level' ];
3110 $where_clauses[] = 'page_id=pr_page';
3113 $cols = [ 'pr_expiry' ];
3116 $res = $dbr->select( $tables, $cols, $where_clauses, __METHOD__
);
3118 $sources = $getPages ?
[] : false;
3119 $now = wfTimestampNow();
3121 foreach ( $res as $row ) {
3122 $expiry = $dbr->decodeExpiry( $row->pr_expiry
);
3123 if ( $expiry > $now ) {
3125 $page_id = $row->pr_page
;
3126 $page_ns = $row->page_namespace
;
3127 $page_title = $row->page_title
;
3128 $sources[$page_id] = self
::makeTitle( $page_ns, $page_title );
3129 # Add groups needed for each restriction type if its not already there
3130 # Make sure this restriction type still exists
3132 if ( !isset( $pagerestrictions[$row->pr_type
] ) ) {
3133 $pagerestrictions[$row->pr_type
] = [];
3137 isset( $pagerestrictions[$row->pr_type
] )
3138 && !in_array( $row->pr_level
, $pagerestrictions[$row->pr_type
] )
3140 $pagerestrictions[$row->pr_type
][] = $row->pr_level
;
3149 $this->mCascadeSources
= $sources;
3150 $this->mCascadingRestrictions
= $pagerestrictions;
3152 $this->mHasCascadingRestrictions
= $sources;
3155 return [ $sources, $pagerestrictions ];
3159 * Accessor for mRestrictionsLoaded
3161 * @return bool Whether or not the page's restrictions have already been
3162 * loaded from the database
3165 public function areRestrictionsLoaded() {
3166 return $this->mRestrictionsLoaded
;
3170 * Accessor/initialisation for mRestrictions
3172 * @param string $action Action that permission needs to be checked for
3173 * @return array Restriction levels needed to take the action. All levels are
3174 * required. Note that restriction levels are normally user rights, but 'sysop'
3175 * and 'autoconfirmed' are also allowed for backwards compatibility. These should
3176 * be mapped to 'editprotected' and 'editsemiprotected' respectively.
3178 public function getRestrictions( $action ) {
3179 if ( !$this->mRestrictionsLoaded
) {
3180 $this->loadRestrictions();
3182 return $this->mRestrictions
[$action] ??
[];
3186 * Accessor/initialisation for mRestrictions
3188 * @return array Keys are actions, values are arrays as returned by
3189 * Title::getRestrictions()
3192 public function getAllRestrictions() {
3193 if ( !$this->mRestrictionsLoaded
) {
3194 $this->loadRestrictions();
3196 return $this->mRestrictions
;
3200 * Get the expiry time for the restriction against a given action
3202 * @param string $action
3203 * @return string|bool 14-char timestamp, or 'infinity' if the page is protected forever
3204 * or not protected at all, or false if the action is not recognised.
3206 public function getRestrictionExpiry( $action ) {
3207 if ( !$this->mRestrictionsLoaded
) {
3208 $this->loadRestrictions();
3210 return $this->mRestrictionsExpiry
[$action] ??
false;
3214 * Returns cascading restrictions for the current article
3218 function areRestrictionsCascading() {
3219 if ( !$this->mRestrictionsLoaded
) {
3220 $this->loadRestrictions();
3223 return $this->mCascadeRestriction
;
3227 * Compiles list of active page restrictions from both page table (pre 1.10)
3228 * and page_restrictions table for this existing page.
3229 * Public for usage by LiquidThreads.
3231 * @param array $rows Array of db result objects
3232 * @param string|null $oldFashionedRestrictions Comma-separated set of permission keys
3233 * indicating who can move or edit the page from the page table, (pre 1.10) rows.
3234 * Edit and move sections are separated by a colon
3235 * Example: "edit=autoconfirmed,sysop:move=sysop"
3237 public function loadRestrictionsFromRows( $rows, $oldFashionedRestrictions = null ) {
3238 // This function will only read rows from a table that we migrated away
3239 // from before adding READ_LATEST support to loadRestrictions, so we
3240 // don't need to support reading from DB_MASTER here.
3241 $dbr = wfGetDB( DB_REPLICA
);
3243 $restrictionTypes = $this->getRestrictionTypes();
3245 foreach ( $restrictionTypes as $type ) {
3246 $this->mRestrictions
[$type] = [];
3247 $this->mRestrictionsExpiry
[$type] = 'infinity';
3250 $this->mCascadeRestriction
= false;
3252 # Backwards-compatibility: also load the restrictions from the page record (old format).
3253 if ( $oldFashionedRestrictions !== null ) {
3254 $this->mOldRestrictions
= $oldFashionedRestrictions;
3257 if ( $this->mOldRestrictions
=== false ) {
3258 $linkCache = MediaWikiServices
::getInstance()->getLinkCache();
3259 $linkCache->addLinkObj( $this ); # in case we already had an article ID
3260 $this->mOldRestrictions
= $linkCache->getGoodLinkFieldObj( $this, 'restrictions' );
3263 if ( $this->mOldRestrictions
!= '' ) {
3264 foreach ( explode( ':', trim( $this->mOldRestrictions
) ) as $restrict ) {
3265 $temp = explode( '=', trim( $restrict ) );
3266 if ( count( $temp ) == 1 ) {
3267 // old old format should be treated as edit/move restriction
3268 $this->mRestrictions
['edit'] = explode( ',', trim( $temp[0] ) );
3269 $this->mRestrictions
['move'] = explode( ',', trim( $temp[0] ) );
3271 $restriction = trim( $temp[1] );
3272 if ( $restriction != '' ) { // some old entries are empty
3273 $this->mRestrictions
[$temp[0]] = explode( ',', $restriction );
3279 if ( count( $rows ) ) {
3280 # Current system - load second to make them override.
3281 $now = wfTimestampNow();
3283 # Cycle through all the restrictions.
3284 foreach ( $rows as $row ) {
3285 // Don't take care of restrictions types that aren't allowed
3286 if ( !in_array( $row->pr_type
, $restrictionTypes ) ) {
3290 $expiry = $dbr->decodeExpiry( $row->pr_expiry
);
3292 // Only apply the restrictions if they haven't expired!
3293 if ( !$expiry ||
$expiry > $now ) {
3294 $this->mRestrictionsExpiry
[$row->pr_type
] = $expiry;
3295 $this->mRestrictions
[$row->pr_type
] = explode( ',', trim( $row->pr_level
) );
3297 $this->mCascadeRestriction |
= $row->pr_cascade
;
3302 $this->mRestrictionsLoaded
= true;
3306 * Load restrictions from the page_restrictions table
3308 * @param string|null $oldFashionedRestrictions Comma-separated set of permission keys
3309 * indicating who can move or edit the page from the page table, (pre 1.10) rows.
3310 * Edit and move sections are separated by a colon
3311 * Example: "edit=autoconfirmed,sysop:move=sysop"
3312 * @param int $flags A bit field. If self::READ_LATEST is set, skip replicas and read
3313 * from the master DB.
3315 public function loadRestrictions( $oldFashionedRestrictions = null, $flags = 0 ) {
3316 $readLatest = DBAccessObjectUtils
::hasFlags( $flags, self
::READ_LATEST
);
3317 if ( $this->mRestrictionsLoaded
&& !$readLatest ) {
3321 // TODO: should probably pass $flags into getArticleID, but it seems hacky
3322 // to mix READ_LATEST and GAID_FOR_UPDATE, even if they have the same value.
3323 // Maybe deprecate GAID_FOR_UPDATE now that we implement IDBAccessObject?
3324 $id = $this->getArticleID();
3326 $fname = __METHOD__
;
3327 $loadRestrictionsFromDb = function ( Database
$dbr ) use ( $fname, $id ) {
3328 return iterator_to_array(
3330 'page_restrictions',
3331 [ 'pr_type', 'pr_expiry', 'pr_level', 'pr_cascade' ],
3332 [ 'pr_page' => $id ],
3338 if ( $readLatest ) {
3339 $dbr = wfGetDB( DB_MASTER
);
3340 $rows = $loadRestrictionsFromDb( $dbr );
3342 $cache = MediaWikiServices
::getInstance()->getMainWANObjectCache();
3343 $rows = $cache->getWithSetCallback(
3344 // Page protections always leave a new null revision
3345 $cache->makeKey( 'page-restrictions', $id, $this->getLatestRevID() ),
3347 function ( $curValue, &$ttl, array &$setOpts ) use ( $loadRestrictionsFromDb ) {
3348 $dbr = wfGetDB( DB_REPLICA
);
3350 $setOpts +
= Database
::getCacheSetOptions( $dbr );
3352 return $loadRestrictionsFromDb( $dbr );
3357 $this->loadRestrictionsFromRows( $rows, $oldFashionedRestrictions );
3359 $title_protection = $this->getTitleProtectionInternal();
3361 if ( $title_protection ) {
3362 $now = wfTimestampNow();
3363 $expiry = wfGetDB( DB_REPLICA
)->decodeExpiry( $title_protection['expiry'] );
3365 if ( !$expiry ||
$expiry > $now ) {
3366 // Apply the restrictions
3367 $this->mRestrictionsExpiry
['create'] = $expiry;
3368 $this->mRestrictions
['create'] =
3369 explode( ',', trim( $title_protection['permission'] ) );
3370 } else { // Get rid of the old restrictions
3371 $this->mTitleProtection
= false;
3374 $this->mRestrictionsExpiry
['create'] = 'infinity';
3376 $this->mRestrictionsLoaded
= true;
3381 * Flush the protection cache in this object and force reload from the database.
3382 * This is used when updating protection from WikiPage::doUpdateRestrictions().
3384 public function flushRestrictions() {
3385 $this->mRestrictionsLoaded
= false;
3386 $this->mTitleProtection
= null;
3390 * Purge expired restrictions from the page_restrictions table
3392 * This will purge no more than $wgUpdateRowsPerQuery page_restrictions rows
3394 static function purgeExpiredRestrictions() {
3395 if ( wfReadOnly() ) {
3399 DeferredUpdates
::addUpdate( new AtomicSectionUpdate(
3400 wfGetDB( DB_MASTER
),
3402 function ( IDatabase
$dbw, $fname ) {
3403 $config = MediaWikiServices
::getInstance()->getMainConfig();
3404 $ids = $dbw->selectFieldValues(
3405 'page_restrictions',
3407 [ 'pr_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ],
3409 [ 'LIMIT' => $config->get( 'UpdateRowsPerQuery' ) ] // T135470
3412 $dbw->delete( 'page_restrictions', [ 'pr_id' => $ids ], $fname );
3417 DeferredUpdates
::addUpdate( new AtomicSectionUpdate(
3418 wfGetDB( DB_MASTER
),
3420 function ( IDatabase
$dbw, $fname ) {
3423 [ 'pt_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ],
3431 * Does this have subpages? (Warning, usually requires an extra DB query.)
3435 public function hasSubpages() {
3436 if ( !MWNamespace
::hasSubpages( $this->mNamespace
) ) {
3441 # We dynamically add a member variable for the purpose of this method
3442 # alone to cache the result. There's no point in having it hanging
3443 # around uninitialized in every Title object; therefore we only add it
3444 # if needed and don't declare it statically.
3445 if ( $this->mHasSubpages
=== null ) {
3446 $this->mHasSubpages
= false;
3447 $subpages = $this->getSubpages( 1 );
3448 if ( $subpages instanceof TitleArray
) {
3449 $this->mHasSubpages
= (bool)$subpages->count();
3453 return $this->mHasSubpages
;
3457 * Get all subpages of this page.
3459 * @param int $limit Maximum number of subpages to fetch; -1 for no limit
3460 * @return TitleArray|array TitleArray, or empty array if this page's namespace
3461 * doesn't allow subpages
3463 public function getSubpages( $limit = -1 ) {
3464 if ( !MWNamespace
::hasSubpages( $this->mNamespace
) ) {
3468 $dbr = wfGetDB( DB_REPLICA
);
3469 $conds['page_namespace'] = $this->mNamespace
;
3470 $conds[] = 'page_title ' . $dbr->buildLike( $this->mDbkeyform
. '/', $dbr->anyString() );
3472 if ( $limit > -1 ) {
3473 $options['LIMIT'] = $limit;
3475 return TitleArray
::newFromResult(
3476 $dbr->select( 'page',
3477 [ 'page_id', 'page_namespace', 'page_title', 'page_is_redirect' ],
3486 * Is there a version of this page in the deletion archive?
3488 * @return int The number of archived revisions
3490 public function isDeleted() {
3491 if ( $this->mNamespace
< 0 ) {
3494 $dbr = wfGetDB( DB_REPLICA
);
3496 $n = $dbr->selectField( 'archive', 'COUNT(*)',
3497 [ 'ar_namespace' => $this->mNamespace
, 'ar_title' => $this->mDbkeyform
],
3500 if ( $this->mNamespace
== NS_FILE
) {
3501 $n +
= $dbr->selectField( 'filearchive', 'COUNT(*)',
3502 [ 'fa_name' => $this->mDbkeyform
],
3511 * Is there a version of this page in the deletion archive?
3515 public function isDeletedQuick() {
3516 if ( $this->mNamespace
< 0 ) {
3519 $dbr = wfGetDB( DB_REPLICA
);
3520 $deleted = (bool)$dbr->selectField( 'archive', '1',
3521 [ 'ar_namespace' => $this->mNamespace
, 'ar_title' => $this->mDbkeyform
],
3524 if ( !$deleted && $this->mNamespace
== NS_FILE
) {
3525 $deleted = (bool)$dbr->selectField( 'filearchive', '1',
3526 [ 'fa_name' => $this->mDbkeyform
],
3534 * Get the article ID for this Title from the link cache,
3535 * adding it if necessary
3537 * @param int $flags A bit field; may be Title::GAID_FOR_UPDATE to select
3539 * @return int The ID
3541 public function getArticleID( $flags = 0 ) {
3542 if ( $this->mNamespace
< 0 ) {
3543 $this->mArticleID
= 0;
3544 return $this->mArticleID
;
3546 $linkCache = MediaWikiServices
::getInstance()->getLinkCache();
3547 if ( $flags & self
::GAID_FOR_UPDATE
) {
3548 $oldUpdate = $linkCache->forUpdate( true );
3549 $linkCache->clearLink( $this );
3550 $this->mArticleID
= $linkCache->addLinkObj( $this );
3551 $linkCache->forUpdate( $oldUpdate );
3553 if ( $this->mArticleID
== -1 ) {
3554 $this->mArticleID
= $linkCache->addLinkObj( $this );
3557 return $this->mArticleID
;
3561 * Is this an article that is a redirect page?
3562 * Uses link cache, adding it if necessary
3564 * @param int $flags A bit field; may be Title::GAID_FOR_UPDATE to select for update
3567 public function isRedirect( $flags = 0 ) {
3568 if ( !is_null( $this->mRedirect
) ) {
3569 return $this->mRedirect
;
3571 if ( !$this->getArticleID( $flags ) ) {
3572 $this->mRedirect
= false;
3573 return $this->mRedirect
;
3576 $linkCache = MediaWikiServices
::getInstance()->getLinkCache();
3577 $linkCache->addLinkObj( $this ); # in case we already had an article ID
3578 $cached = $linkCache->getGoodLinkFieldObj( $this, 'redirect' );
3579 if ( $cached === null ) {
3580 # Trust LinkCache's state over our own
3581 # LinkCache is telling us that the page doesn't exist, despite there being cached
3582 # data relating to an existing page in $this->mArticleID. Updaters should clear
3583 # LinkCache as appropriate, or use $flags = Title::GAID_FOR_UPDATE. If that flag is
3584 # set, then LinkCache will definitely be up to date here, since getArticleID() forces
3585 # LinkCache to refresh its data from the master.
3586 $this->mRedirect
= false;
3587 return $this->mRedirect
;
3590 $this->mRedirect
= (bool)$cached;
3592 return $this->mRedirect
;
3596 * What is the length of this page?
3597 * Uses link cache, adding it if necessary
3599 * @param int $flags A bit field; may be Title::GAID_FOR_UPDATE to select for update
3602 public function getLength( $flags = 0 ) {
3603 if ( $this->mLength
!= -1 ) {
3604 return $this->mLength
;
3606 if ( !$this->getArticleID( $flags ) ) {
3608 return $this->mLength
;
3610 $linkCache = MediaWikiServices
::getInstance()->getLinkCache();
3611 $linkCache->addLinkObj( $this ); # in case we already had an article ID
3612 $cached = $linkCache->getGoodLinkFieldObj( $this, 'length' );
3613 if ( $cached === null ) {
3614 # Trust LinkCache's state over our own, as for isRedirect()
3616 return $this->mLength
;
3619 $this->mLength
= intval( $cached );
3621 return $this->mLength
;
3625 * What is the page_latest field for this page?
3627 * @param int $flags A bit field; may be Title::GAID_FOR_UPDATE to select for update
3628 * @return int Int or 0 if the page doesn't exist
3630 public function getLatestRevID( $flags = 0 ) {
3631 if ( !( $flags & self
::GAID_FOR_UPDATE
) && $this->mLatestID
!== false ) {
3632 return intval( $this->mLatestID
);
3634 if ( !$this->getArticleID( $flags ) ) {
3635 $this->mLatestID
= 0;
3636 return $this->mLatestID
;
3638 $linkCache = MediaWikiServices
::getInstance()->getLinkCache();
3639 $linkCache->addLinkObj( $this ); # in case we already had an article ID
3640 $cached = $linkCache->getGoodLinkFieldObj( $this, 'revision' );
3641 if ( $cached === null ) {
3642 # Trust LinkCache's state over our own, as for isRedirect()
3643 $this->mLatestID
= 0;
3644 return $this->mLatestID
;
3647 $this->mLatestID
= intval( $cached );
3649 return $this->mLatestID
;
3653 * This clears some fields in this object, and clears any associated
3654 * keys in the "bad links" section of the link cache.
3656 * - This is called from WikiPage::doEditContent() and WikiPage::insertOn() to allow
3657 * loading of the new page_id. It's also called from
3658 * WikiPage::doDeleteArticleReal()
3660 * @param int $newid The new Article ID
3662 public function resetArticleID( $newid ) {
3663 $linkCache = MediaWikiServices
::getInstance()->getLinkCache();
3664 $linkCache->clearLink( $this );
3666 if ( $newid === false ) {
3667 $this->mArticleID
= -1;
3669 $this->mArticleID
= intval( $newid );
3671 $this->mRestrictionsLoaded
= false;
3672 $this->mRestrictions
= [];
3673 $this->mOldRestrictions
= false;
3674 $this->mRedirect
= null;
3675 $this->mLength
= -1;
3676 $this->mLatestID
= false;
3677 $this->mContentModel
= false;
3678 $this->mEstimateRevisions
= null;
3679 $this->mPageLanguage
= false;
3680 $this->mDbPageLanguage
= false;
3681 $this->mIsBigDeletion
= null;
3684 public static function clearCaches() {
3685 $linkCache = MediaWikiServices
::getInstance()->getLinkCache();
3686 $linkCache->clear();
3688 $titleCache = self
::getTitleCache();
3689 $titleCache->clear();
3693 * Capitalize a text string for a title if it belongs to a namespace that capitalizes
3695 * @param string $text Containing title to capitalize
3696 * @param int $ns Namespace index, defaults to NS_MAIN
3697 * @return string Containing capitalized title
3699 public static function capitalize( $text, $ns = NS_MAIN
) {
3700 if ( MWNamespace
::isCapitalized( $ns ) ) {
3701 return MediaWikiServices
::getInstance()->getContentLanguage()->ucfirst( $text );
3708 * Secure and split - main initialisation function for this object
3710 * Assumes that mDbkeyform has been set, and is urldecoded
3711 * and uses underscores, but not otherwise munged. This function
3712 * removes illegal characters, splits off the interwiki and
3713 * namespace prefixes, sets the other forms, and canonicalizes
3716 * @throws MalformedTitleException On invalid titles
3717 * @return bool True on success
3719 private function secureAndSplit() {
3720 // @note: splitTitleString() is a temporary hack to allow MediaWikiTitleCodec to share
3721 // the parsing code with Title, while avoiding massive refactoring.
3722 // @todo: get rid of secureAndSplit, refactor parsing code.
3723 // @note: getTitleParser() returns a TitleParser implementation which does not have a
3724 // splitTitleString method, but the only implementation (MediaWikiTitleCodec) does
3725 $titleCodec = MediaWikiServices
::getInstance()->getTitleParser();
3726 // MalformedTitleException can be thrown here
3727 $parts = $titleCodec->splitTitleString( $this->mDbkeyform
, $this->mDefaultNamespace
);
3730 $this->setFragment( '#' . $parts['fragment'] );
3731 $this->mInterwiki
= $parts['interwiki'];
3732 $this->mLocalInterwiki
= $parts['local_interwiki'];
3733 $this->mNamespace
= $parts['namespace'];
3734 $this->mUserCaseDBKey
= $parts['user_case_dbkey'];
3736 $this->mDbkeyform
= $parts['dbkey'];
3737 $this->mUrlform
= wfUrlencode( $this->mDbkeyform
);
3738 $this->mTextform
= strtr( $this->mDbkeyform
, '_', ' ' );
3740 # We already know that some pages won't be in the database!
3741 if ( $this->isExternal() ||
$this->isSpecialPage() ) {
3742 $this->mArticleID
= 0;
3749 * Get an array of Title objects linking to this Title
3750 * Also stores the IDs in the link cache.
3752 * WARNING: do not use this function on arbitrary user-supplied titles!
3753 * On heavily-used templates it will max out the memory.
3755 * @param array $options May be FOR UPDATE
3756 * @param string $table Table name
3757 * @param string $prefix Fields prefix
3758 * @return Title[] Array of Title objects linking here
3760 public function getLinksTo( $options = [], $table = 'pagelinks', $prefix = 'pl' ) {
3761 if ( count( $options ) > 0 ) {
3762 $db = wfGetDB( DB_MASTER
);
3764 $db = wfGetDB( DB_REPLICA
);
3769 self
::getSelectFields(),
3771 "{$prefix}_from=page_id",
3772 "{$prefix}_namespace" => $this->mNamespace
,
3773 "{$prefix}_title" => $this->mDbkeyform
],
3779 if ( $res->numRows() ) {
3780 $linkCache = MediaWikiServices
::getInstance()->getLinkCache();
3781 foreach ( $res as $row ) {
3782 $titleObj = self
::makeTitle( $row->page_namespace
, $row->page_title
);
3784 $linkCache->addGoodLinkObjFromRow( $titleObj, $row );
3785 $retVal[] = $titleObj;
3793 * Get an array of Title objects using this Title as a template
3794 * Also stores the IDs in the link cache.
3796 * WARNING: do not use this function on arbitrary user-supplied titles!
3797 * On heavily-used templates it will max out the memory.
3799 * @param array $options Query option to Database::select()
3800 * @return Title[] Array of Title the Title objects linking here
3802 public function getTemplateLinksTo( $options = [] ) {
3803 return $this->getLinksTo( $options, 'templatelinks', 'tl' );
3807 * Get an array of Title objects linked from this Title
3808 * Also stores the IDs in the link cache.
3810 * WARNING: do not use this function on arbitrary user-supplied titles!
3811 * On heavily-used templates it will max out the memory.
3813 * @param array $options Query option to Database::select()
3814 * @param string $table Table name
3815 * @param string $prefix Fields prefix
3816 * @return array Array of Title objects linking here
3818 public function getLinksFrom( $options = [], $table = 'pagelinks', $prefix = 'pl' ) {
3819 $id = $this->getArticleID();
3821 # If the page doesn't exist; there can't be any link from this page
3826 $db = wfGetDB( DB_REPLICA
);
3828 $blNamespace = "{$prefix}_namespace";
3829 $blTitle = "{$prefix}_title";
3831 $pageQuery = WikiPage
::getQueryInfo();
3833 [ $table, 'nestpage' => $pageQuery['tables'] ],
3835 [ $blNamespace, $blTitle ],
3836 $pageQuery['fields']
3838 [ "{$prefix}_from" => $id ],
3843 [ "page_namespace=$blNamespace", "page_title=$blTitle" ]
3844 ] ] +
$pageQuery['joins']
3848 $linkCache = MediaWikiServices
::getInstance()->getLinkCache();
3849 foreach ( $res as $row ) {
3850 if ( $row->page_id
) {
3851 $titleObj = self
::newFromRow( $row );
3853 $titleObj = self
::makeTitle( $row->$blNamespace, $row->$blTitle );
3854 $linkCache->addBadLinkObj( $titleObj );
3856 $retVal[] = $titleObj;
3863 * Get an array of Title objects used on this Title as a template
3864 * Also stores the IDs in the link cache.
3866 * WARNING: do not use this function on arbitrary user-supplied titles!
3867 * On heavily-used templates it will max out the memory.
3869 * @param array $options May be FOR UPDATE
3870 * @return Title[] Array of Title the Title objects used here
3872 public function getTemplateLinksFrom( $options = [] ) {
3873 return $this->getLinksFrom( $options, 'templatelinks', 'tl' );
3877 * Get an array of Title objects referring to non-existent articles linked
3880 * @todo check if needed (used only in SpecialBrokenRedirects.php, and
3881 * should use redirect table in this case).
3882 * @return Title[] Array of Title the Title objects
3884 public function getBrokenLinksFrom() {
3885 if ( $this->getArticleID() == 0 ) {
3886 # All links from article ID 0 are false positives
3890 $dbr = wfGetDB( DB_REPLICA
);
3891 $res = $dbr->select(
3892 [ 'page', 'pagelinks' ],
3893 [ 'pl_namespace', 'pl_title' ],
3895 'pl_from' => $this->getArticleID(),
3896 'page_namespace IS NULL'
3902 [ 'pl_namespace=page_namespace', 'pl_title=page_title' ]
3908 foreach ( $res as $row ) {
3909 $retVal[] = self
::makeTitle( $row->pl_namespace
, $row->pl_title
);
3915 * Get a list of URLs to purge from the CDN cache when this
3918 * @return string[] Array of String the URLs
3920 public function getCdnUrls() {
3922 $this->getInternalURL(),
3923 $this->getInternalURL( 'action=history' )
3926 $pageLang = $this->getPageLanguage();
3927 if ( $pageLang->hasVariants() ) {
3928 $variants = $pageLang->getVariants();
3929 foreach ( $variants as $vCode ) {
3930 $urls[] = $this->getInternalURL( $vCode );
3934 // If we are looking at a css/js user subpage, purge the action=raw.
3935 if ( $this->isUserJsConfigPage() ) {
3936 $urls[] = $this->getInternalURL( 'action=raw&ctype=text/javascript' );
3937 } elseif ( $this->isUserJsonConfigPage() ) {
3938 $urls[] = $this->getInternalURL( 'action=raw&ctype=application/json' );
3939 } elseif ( $this->isUserCssConfigPage() ) {
3940 $urls[] = $this->getInternalURL( 'action=raw&ctype=text/css' );
3943 Hooks
::run( 'TitleSquidURLs', [ $this, &$urls ] );
3948 * Purge all applicable CDN URLs
3950 public function purgeSquid() {
3951 DeferredUpdates
::addUpdate(
3952 new CdnCacheUpdate( $this->getCdnUrls() ),
3953 DeferredUpdates
::PRESEND
3958 * Check whether a given move operation would be valid.
3959 * Returns true if ok, or a getUserPermissionsErrors()-like array otherwise
3961 * @deprecated since 1.25, use MovePage's methods instead
3962 * @param Title &$nt The new title
3963 * @param bool $auth Whether to check user permissions (uses $wgUser)
3964 * @param string $reason Is the log summary of the move, used for spam checking
3965 * @return array|bool True on success, getUserPermissionsErrors()-like array on failure
3967 public function isValidMoveOperation( &$nt, $auth = true, $reason = '' ) {
3970 if ( !( $nt instanceof Title
) ) {
3971 // Normally we'd add this to $errors, but we'll get
3972 // lots of syntax errors if $nt is not an object
3973 return [ [ 'badtitletext' ] ];
3976 $mp = new MovePage( $this, $nt );
3977 $errors = $mp->isValidMove()->getErrorsArray();
3979 $errors = wfMergeErrorArrays(
3981 $mp->checkPermissions( $wgUser, $reason )->getErrorsArray()
3985 return $errors ?
: true;
3989 * Move a title to a new location
3991 * @deprecated since 1.25, use the MovePage class instead
3992 * @param Title &$nt The new title
3993 * @param bool $auth Indicates whether $wgUser's permissions
3995 * @param string $reason The reason for the move
3996 * @param bool $createRedirect Whether to create a redirect from the old title to the new title.
3997 * Ignored if the user doesn't have the suppressredirect right.
3998 * @param array $changeTags Applied to the entry in the move log and redirect page revision
3999 * @return array|bool True on success, getUserPermissionsErrors()-like array on failure
4001 public function moveTo( &$nt, $auth = true, $reason = '', $createRedirect = true,
4002 array $changeTags = []
4005 $err = $this->isValidMoveOperation( $nt, $auth, $reason );
4006 if ( is_array( $err ) ) {
4007 // Auto-block user's IP if the account was "hard" blocked
4008 $wgUser->spreadAnyEditBlock();
4011 // Check suppressredirect permission
4012 if ( $auth && !$wgUser->isAllowed( 'suppressredirect' ) ) {
4013 $createRedirect = true;
4016 $mp = new MovePage( $this, $nt );
4017 $status = $mp->move( $wgUser, $reason, $createRedirect, $changeTags );
4018 if ( $status->isOK() ) {
4021 return $status->getErrorsArray();
4026 * Move this page's subpages to be subpages of $nt
4028 * @param Title $nt Move target
4029 * @param bool $auth Whether $wgUser's permissions should be checked
4030 * @param string $reason The reason for the move
4031 * @param bool $createRedirect Whether to create redirects from the old subpages to
4032 * the new ones Ignored if the user doesn't have the 'suppressredirect' right
4033 * @param array $changeTags Applied to the entry in the move log and redirect page revision
4034 * @return array Array with old page titles as keys, and strings (new page titles) or
4035 * getUserPermissionsErrors()-like arrays (errors) as values, or a
4036 * getUserPermissionsErrors()-like error array with numeric indices if
4037 * no pages were moved
4039 public function moveSubpages( $nt, $auth = true, $reason = '', $createRedirect = true,
4040 array $changeTags = []
4042 global $wgMaximumMovedPages;
4043 // Check permissions
4044 if ( !$this->userCan( 'move-subpages' ) ) {
4046 [ 'cant-move-subpages' ],
4049 // Do the source and target namespaces support subpages?
4050 if ( !MWNamespace
::hasSubpages( $this->mNamespace
) ) {
4052 [ 'namespace-nosubpages', MWNamespace
::getCanonicalName( $this->mNamespace
) ],
4055 if ( !MWNamespace
::hasSubpages( $nt->getNamespace() ) ) {
4057 [ 'namespace-nosubpages', MWNamespace
::getCanonicalName( $nt->getNamespace() ) ],
4061 $subpages = $this->getSubpages( $wgMaximumMovedPages +
1 );
4064 foreach ( $subpages as $oldSubpage ) {
4066 if ( $count > $wgMaximumMovedPages ) {
4067 $retval[$oldSubpage->getPrefixedText()] = [
4068 [ 'movepage-max-pages', $wgMaximumMovedPages ],
4073 // We don't know whether this function was called before
4074 // or after moving the root page, so check both
4076 if ( $oldSubpage->getArticleID() == $this->getArticleID()
4077 ||
$oldSubpage->getArticleID() == $nt->getArticleID()
4079 // When moving a page to a subpage of itself,
4080 // don't move it twice
4083 $newPageName = preg_replace(
4084 '#^' . preg_quote( $this->mDbkeyform
, '#' ) . '#',
4085 StringUtils
::escapeRegexReplacement( $nt->getDBkey() ), # T23234
4086 $oldSubpage->getDBkey() );
4087 if ( $oldSubpage->isTalkPage() ) {
4088 $newNs = $nt->getTalkPage()->getNamespace();
4090 $newNs = $nt->getSubjectPage()->getNamespace();
4092 # T16385: we need makeTitleSafe because the new page names may
4093 # be longer than 255 characters.
4094 $newSubpage = self
::makeTitleSafe( $newNs, $newPageName );
4096 $success = $oldSubpage->moveTo( $newSubpage, $auth, $reason, $createRedirect, $changeTags );
4097 if ( $success === true ) {
4098 $retval[$oldSubpage->getPrefixedText()] = $newSubpage->getPrefixedText();
4100 $retval[$oldSubpage->getPrefixedText()] = $success;
4107 * Checks if this page is just a one-rev redirect.
4108 * Adds lock, so don't use just for light purposes.
4112 public function isSingleRevRedirect() {
4113 global $wgContentHandlerUseDB;
4115 $dbw = wfGetDB( DB_MASTER
);
4118 $fields = [ 'page_is_redirect', 'page_latest', 'page_id' ];
4119 if ( $wgContentHandlerUseDB ) {
4120 $fields[] = 'page_content_model';
4123 $row = $dbw->selectRow( 'page',
4129 # Cache some fields we may want
4130 $this->mArticleID
= $row ?
intval( $row->page_id
) : 0;
4131 $this->mRedirect
= $row ?
(bool)$row->page_is_redirect
: false;
4132 $this->mLatestID
= $row ?
intval( $row->page_latest
) : false;
4133 $this->mContentModel
= $row && isset( $row->page_content_model
)
4134 ?
strval( $row->page_content_model
)
4137 if ( !$this->mRedirect
) {
4140 # Does the article have a history?
4141 $row = $dbw->selectField( [ 'page', 'revision' ],
4143 [ 'page_namespace' => $this->mNamespace
,
4144 'page_title' => $this->mDbkeyform
,
4146 'page_latest != rev_id'
4151 # Return true if there was no history
4152 return ( $row === false );
4156 * Checks if $this can be moved to a given Title
4157 * - Selects for update, so don't call it unless you mean business
4159 * @deprecated since 1.25, use MovePage's methods instead
4160 * @param Title $nt The new title to check
4163 public function isValidMoveTarget( $nt ) {
4164 # Is it an existing file?
4165 if ( $nt->getNamespace() == NS_FILE
) {
4166 $file = wfLocalFile( $nt );
4167 $file->load( File
::READ_LATEST
);
4168 if ( $file->exists() ) {
4169 wfDebug( __METHOD__
. ": file exists\n" );
4173 # Is it a redirect with no history?
4174 if ( !$nt->isSingleRevRedirect() ) {
4175 wfDebug( __METHOD__
. ": not a one-rev redirect\n" );
4178 # Get the article text
4179 $rev = Revision
::newFromTitle( $nt, false, Revision
::READ_LATEST
);
4180 if ( !is_object( $rev ) ) {
4183 $content = $rev->getContent();
4184 # Does the redirect point to the source?
4185 # Or is it a broken self-redirect, usually caused by namespace collisions?
4186 $redirTitle = $content ?
$content->getRedirectTarget() : null;
4188 if ( $redirTitle ) {
4189 if ( $redirTitle->getPrefixedDBkey() != $this->getPrefixedDBkey() &&
4190 $redirTitle->getPrefixedDBkey() != $nt->getPrefixedDBkey() ) {
4191 wfDebug( __METHOD__
. ": redirect points to other page\n" );
4197 # Fail safe (not a redirect after all. strange.)
4198 wfDebug( __METHOD__
. ": failsafe: database sais " . $nt->getPrefixedDBkey() .
4199 " is a redirect, but it doesn't contain a valid redirect.\n" );
4205 * Get categories to which this Title belongs and return an array of
4206 * categories' names.
4208 * @return array Array of parents in the form:
4209 * $parent => $currentarticle
4211 public function getParentCategories() {
4214 $titleKey = $this->getArticleID();
4216 if ( $titleKey === 0 ) {
4220 $dbr = wfGetDB( DB_REPLICA
);
4222 $res = $dbr->select(
4225 [ 'cl_from' => $titleKey ],
4229 if ( $res->numRows() > 0 ) {
4230 $contLang = MediaWikiServices
::getInstance()->getContentLanguage();
4231 foreach ( $res as $row ) {
4232 // $data[] = Title::newFromText( $contLang->getNsText ( NS_CATEGORY ).':'.$row->cl_to);
4233 $data[$contLang->getNsText( NS_CATEGORY
) . ':' . $row->cl_to
] =
4234 $this->getFullText();
4241 * Get a tree of parent categories
4243 * @param array $children Array with the children in the keys, to check for circular refs
4244 * @return array Tree of parent categories
4246 public function getParentCategoryTree( $children = [] ) {
4248 $parents = $this->getParentCategories();
4251 foreach ( $parents as $parent => $current ) {
4252 if ( array_key_exists( $parent, $children ) ) {
4253 # Circular reference
4254 $stack[$parent] = [];
4256 $nt = self
::newFromText( $parent );
4258 $stack[$parent] = $nt->getParentCategoryTree( $children +
[ $parent => 1 ] );
4268 * Get an associative array for selecting this title from
4271 * @return array Array suitable for the $where parameter of DB::select()
4273 public function pageCond() {
4274 if ( $this->mArticleID
> 0 ) {
4275 // PK avoids secondary lookups in InnoDB, shouldn't hurt other DBs
4276 return [ 'page_id' => $this->mArticleID
];
4278 return [ 'page_namespace' => $this->mNamespace
, 'page_title' => $this->mDbkeyform
];
4283 * Get next/previous revision ID relative to another revision ID
4284 * @param int $revId Revision ID. Get the revision that was before this one.
4285 * @param int $flags Title::GAID_FOR_UPDATE
4286 * @param string $dir 'next' or 'prev'
4287 * @return int|bool New revision ID, or false if none exists
4289 private function getRelativeRevisionID( $revId, $flags, $dir ) {
4290 $revId = (int)$revId;
4291 if ( $dir === 'next' ) {
4294 } elseif ( $dir === 'prev' ) {
4298 throw new InvalidArgumentException( '$dir must be "next" or "prev"' );
4301 if ( $flags & self
::GAID_FOR_UPDATE
) {
4302 $db = wfGetDB( DB_MASTER
);
4304 $db = wfGetDB( DB_REPLICA
, 'contributions' );
4307 // Intentionally not caring if the specified revision belongs to this
4308 // page. We only care about the timestamp.
4309 $ts = $db->selectField( 'revision', 'rev_timestamp', [ 'rev_id' => $revId ], __METHOD__
);
4310 if ( $ts === false ) {
4311 $ts = $db->selectField( 'archive', 'ar_timestamp', [ 'ar_rev_id' => $revId ], __METHOD__
);
4312 if ( $ts === false ) {
4313 // Or should this throw an InvalidArgumentException or something?
4317 $ts = $db->addQuotes( $ts );
4319 $revId = $db->selectField( 'revision', 'rev_id',
4321 'rev_page' => $this->getArticleID( $flags ),
4322 "rev_timestamp $op $ts OR (rev_timestamp = $ts AND rev_id $op $revId)"
4326 'ORDER BY' => "rev_timestamp $sort, rev_id $sort",
4327 'IGNORE INDEX' => 'rev_timestamp', // Probably needed for T159319
4331 if ( $revId === false ) {
4334 return intval( $revId );
4339 * Get the revision ID of the previous revision
4341 * @param int $revId Revision ID. Get the revision that was before this one.
4342 * @param int $flags Title::GAID_FOR_UPDATE
4343 * @return int|bool Old revision ID, or false if none exists
4345 public function getPreviousRevisionID( $revId, $flags = 0 ) {
4346 return $this->getRelativeRevisionID( $revId, $flags, 'prev' );
4350 * Get the revision ID of the next revision
4352 * @param int $revId Revision ID. Get the revision that was after this one.
4353 * @param int $flags Title::GAID_FOR_UPDATE
4354 * @return int|bool Next revision ID, or false if none exists
4356 public function getNextRevisionID( $revId, $flags = 0 ) {
4357 return $this->getRelativeRevisionID( $revId, $flags, 'next' );
4361 * Get the first revision of the page
4363 * @param int $flags Title::GAID_FOR_UPDATE
4364 * @return Revision|null If page doesn't exist
4366 public function getFirstRevision( $flags = 0 ) {
4367 $pageId = $this->getArticleID( $flags );
4369 $db = ( $flags & self
::GAID_FOR_UPDATE
) ?
wfGetDB( DB_MASTER
) : wfGetDB( DB_REPLICA
);
4370 $revQuery = Revision
::getQueryInfo();
4371 $row = $db->selectRow( $revQuery['tables'], $revQuery['fields'],
4372 [ 'rev_page' => $pageId ],
4375 'ORDER BY' => 'rev_timestamp ASC, rev_id ASC',
4376 'IGNORE INDEX' => [ 'revision' => 'rev_timestamp' ], // See T159319
4381 return new Revision( $row, 0, $this );
4388 * Get the oldest revision timestamp of this page
4390 * @param int $flags Title::GAID_FOR_UPDATE
4391 * @return string|null MW timestamp
4393 public function getEarliestRevTime( $flags = 0 ) {
4394 $rev = $this->getFirstRevision( $flags );
4395 return $rev ?
$rev->getTimestamp() : null;
4399 * Check if this is a new page
4403 public function isNewPage() {
4404 $dbr = wfGetDB( DB_REPLICA
);
4405 return (bool)$dbr->selectField( 'page', 'page_is_new', $this->pageCond(), __METHOD__
);
4409 * Check whether the number of revisions of this page surpasses $wgDeleteRevisionsLimit
4413 public function isBigDeletion() {
4414 global $wgDeleteRevisionsLimit;
4416 if ( !$wgDeleteRevisionsLimit ) {
4420 if ( $this->mIsBigDeletion
=== null ) {
4421 $dbr = wfGetDB( DB_REPLICA
);
4423 $revCount = $dbr->selectRowCount(
4426 [ 'rev_page' => $this->getArticleID() ],
4428 [ 'LIMIT' => $wgDeleteRevisionsLimit +
1 ]
4431 $this->mIsBigDeletion
= $revCount > $wgDeleteRevisionsLimit;
4434 return $this->mIsBigDeletion
;
4438 * Get the approximate revision count of this page.
4442 public function estimateRevisionCount() {
4443 if ( !$this->exists() ) {
4447 if ( $this->mEstimateRevisions
=== null ) {
4448 $dbr = wfGetDB( DB_REPLICA
);
4449 $this->mEstimateRevisions
= $dbr->estimateRowCount( 'revision', '*',
4450 [ 'rev_page' => $this->getArticleID() ], __METHOD__
);
4453 return $this->mEstimateRevisions
;
4457 * Get the number of revisions between the given revision.
4458 * Used for diffs and other things that really need it.
4460 * @param int|Revision $old Old revision or rev ID (first before range)
4461 * @param int|Revision $new New revision or rev ID (first after range)
4462 * @param int|null $max Limit of Revisions to count, will be incremented to detect truncations
4463 * @return int Number of revisions between these revisions.
4465 public function countRevisionsBetween( $old, $new, $max = null ) {
4466 if ( !( $old instanceof Revision
) ) {
4467 $old = Revision
::newFromTitle( $this, (int)$old );
4469 if ( !( $new instanceof Revision
) ) {
4470 $new = Revision
::newFromTitle( $this, (int)$new );
4472 if ( !$old ||
!$new ) {
4473 return 0; // nothing to compare
4475 $dbr = wfGetDB( DB_REPLICA
);
4477 'rev_page' => $this->getArticleID(),
4478 'rev_timestamp > ' . $dbr->addQuotes( $dbr->timestamp( $old->getTimestamp() ) ),
4479 'rev_timestamp < ' . $dbr->addQuotes( $dbr->timestamp( $new->getTimestamp() ) )
4481 if ( $max !== null ) {
4482 return $dbr->selectRowCount( 'revision', '1',
4485 [ 'LIMIT' => $max +
1 ] // extra to detect truncation
4488 return (int)$dbr->selectField( 'revision', 'count(*)', $conds, __METHOD__
);
4493 * Get the authors between the given revisions or revision IDs.
4494 * Used for diffs and other things that really need it.
4498 * @param int|Revision $old Old revision or rev ID (first before range by default)
4499 * @param int|Revision $new New revision or rev ID (first after range by default)
4500 * @param int $limit Maximum number of authors
4501 * @param string|array $options (Optional): Single option, or an array of options:
4502 * 'include_old' Include $old in the range; $new is excluded.
4503 * 'include_new' Include $new in the range; $old is excluded.
4504 * 'include_both' Include both $old and $new in the range.
4505 * Unknown option values are ignored.
4506 * @return array|null Names of revision authors in the range; null if not both revisions exist
4508 public function getAuthorsBetween( $old, $new, $limit, $options = [] ) {
4509 if ( !( $old instanceof Revision
) ) {
4510 $old = Revision
::newFromTitle( $this, (int)$old );
4512 if ( !( $new instanceof Revision
) ) {
4513 $new = Revision
::newFromTitle( $this, (int)$new );
4515 // XXX: what if Revision objects are passed in, but they don't refer to this title?
4516 // Add $old->getPage() != $new->getPage() || $old->getPage() != $this->getArticleID()
4517 // in the sanity check below?
4518 if ( !$old ||
!$new ) {
4519 return null; // nothing to compare
4524 $options = (array)$options;
4525 if ( in_array( 'include_old', $options ) ) {
4528 if ( in_array( 'include_new', $options ) ) {
4531 if ( in_array( 'include_both', $options ) ) {
4535 // No DB query needed if $old and $new are the same or successive revisions:
4536 if ( $old->getId() === $new->getId() ) {
4537 return ( $old_cmp === '>' && $new_cmp === '<' ) ?
4539 [ $old->getUserText( Revision
::RAW
) ];
4540 } elseif ( $old->getId() === $new->getParentId() ) {
4541 if ( $old_cmp === '>=' && $new_cmp === '<=' ) {
4542 $authors[] = $old->getUserText( Revision
::RAW
);
4543 if ( $old->getUserText( Revision
::RAW
) != $new->getUserText( Revision
::RAW
) ) {
4544 $authors[] = $new->getUserText( Revision
::RAW
);
4546 } elseif ( $old_cmp === '>=' ) {
4547 $authors[] = $old->getUserText( Revision
::RAW
);
4548 } elseif ( $new_cmp === '<=' ) {
4549 $authors[] = $new->getUserText( Revision
::RAW
);
4553 $dbr = wfGetDB( DB_REPLICA
);
4554 $revQuery = Revision
::getQueryInfo();
4555 $authors = $dbr->selectFieldValues(
4556 $revQuery['tables'],
4557 $revQuery['fields']['rev_user_text'],
4559 'rev_page' => $this->getArticleID(),
4560 "rev_timestamp $old_cmp " . $dbr->addQuotes( $dbr->timestamp( $old->getTimestamp() ) ),
4561 "rev_timestamp $new_cmp " . $dbr->addQuotes( $dbr->timestamp( $new->getTimestamp() ) )
4563 [ 'DISTINCT', 'LIMIT' => $limit +
1 ], // add one so caller knows it was truncated
4570 * Get the number of authors between the given revisions or revision IDs.
4571 * Used for diffs and other things that really need it.
4573 * @param int|Revision $old Old revision or rev ID (first before range by default)
4574 * @param int|Revision $new New revision or rev ID (first after range by default)
4575 * @param int $limit Maximum number of authors
4576 * @param string|array $options (Optional): Single option, or an array of options:
4577 * 'include_old' Include $old in the range; $new is excluded.
4578 * 'include_new' Include $new in the range; $old is excluded.
4579 * 'include_both' Include both $old and $new in the range.
4580 * Unknown option values are ignored.
4581 * @return int Number of revision authors in the range; zero if not both revisions exist
4583 public function countAuthorsBetween( $old, $new, $limit, $options = [] ) {
4584 $authors = $this->getAuthorsBetween( $old, $new, $limit, $options );
4585 return $authors ?
count( $authors ) : 0;
4589 * Compare with another title.
4591 * @param Title $title
4594 public function equals( Title
$title ) {
4595 // Note: === is necessary for proper matching of number-like titles.
4596 return $this->mInterwiki
=== $title->mInterwiki
4597 && $this->mNamespace
== $title->mNamespace
4598 && $this->mDbkeyform
=== $title->mDbkeyform
;
4602 * Check if this title is a subpage of another title
4604 * @param Title $title
4607 public function isSubpageOf( Title
$title ) {
4608 return $this->mInterwiki
=== $title->mInterwiki
4609 && $this->mNamespace
== $title->mNamespace
4610 && strpos( $this->mDbkeyform
, $title->mDbkeyform
. '/' ) === 0;
4614 * Check if page exists. For historical reasons, this function simply
4615 * checks for the existence of the title in the page table, and will
4616 * thus return false for interwiki links, special pages and the like.
4617 * If you want to know if a title can be meaningfully viewed, you should
4618 * probably call the isKnown() method instead.
4620 * @param int $flags An optional bit field; may be Title::GAID_FOR_UPDATE to check
4621 * from master/for update
4624 public function exists( $flags = 0 ) {
4625 $exists = $this->getArticleID( $flags ) != 0;
4626 Hooks
::run( 'TitleExists', [ $this, &$exists ] );
4631 * Should links to this title be shown as potentially viewable (i.e. as
4632 * "bluelinks"), even if there's no record by this title in the page
4635 * This function is semi-deprecated for public use, as well as somewhat
4636 * misleadingly named. You probably just want to call isKnown(), which
4637 * calls this function internally.
4639 * (ISSUE: Most of these checks are cheap, but the file existence check
4640 * can potentially be quite expensive. Including it here fixes a lot of
4641 * existing code, but we might want to add an optional parameter to skip
4642 * it and any other expensive checks.)
4646 public function isAlwaysKnown() {
4650 * Allows overriding default behavior for determining if a page exists.
4651 * If $isKnown is kept as null, regular checks happen. If it's
4652 * a boolean, this value is returned by the isKnown method.
4656 * @param Title $title
4657 * @param bool|null $isKnown
4659 Hooks
::run( 'TitleIsAlwaysKnown', [ $this, &$isKnown ] );
4661 if ( !is_null( $isKnown ) ) {
4665 if ( $this->isExternal() ) {
4666 return true; // any interwiki link might be viewable, for all we know
4669 switch ( $this->mNamespace
) {
4672 // file exists, possibly in a foreign repo
4673 return (bool)wfFindFile( $this );
4675 // valid special page
4676 return MediaWikiServices
::getInstance()->getSpecialPageFactory()->
4677 exists( $this->mDbkeyform
);
4679 // selflink, possibly with fragment
4680 return $this->mDbkeyform
== '';
4682 // known system message
4683 return $this->hasSourceText() !== false;
4690 * Does this title refer to a page that can (or might) be meaningfully
4691 * viewed? In particular, this function may be used to determine if
4692 * links to the title should be rendered as "bluelinks" (as opposed to
4693 * "redlinks" to non-existent pages).
4694 * Adding something else to this function will cause inconsistency
4695 * since LinkHolderArray calls isAlwaysKnown() and does its own
4696 * page existence check.
4700 public function isKnown() {
4701 return $this->isAlwaysKnown() ||
$this->exists();
4705 * Does this page have source text?
4709 public function hasSourceText() {
4710 if ( $this->exists() ) {
4714 if ( $this->mNamespace
== NS_MEDIAWIKI
) {
4715 // If the page doesn't exist but is a known system message, default
4716 // message content will be displayed, same for language subpages-
4717 // Use always content language to avoid loading hundreds of languages
4718 // to get the link color.
4719 $contLang = MediaWikiServices
::getInstance()->getContentLanguage();
4720 list( $name, ) = MessageCache
::singleton()->figureMessage(
4721 $contLang->lcfirst( $this->getText() )
4723 $message = wfMessage( $name )->inLanguage( $contLang )->useDatabase( false );
4724 return $message->exists();
4731 * Get the default (plain) message contents for an page that overrides an
4732 * interface message key.
4734 * Primary use cases:
4737 * - Show default when viewing the page. The Article::getSubstituteContent
4738 * method displays the default message content, instead of the
4739 * 'noarticletext' placeholder message normally used.
4742 * - Title of edit page. When creating an interface message override,
4743 * the editor is told they are "Editing the page", instead of
4744 * "Creating the page". (EditPage::setHeaders)
4745 * - Edit notice. The 'translateinterface' edit notice is shown when creating
4746 * or editing a an interface message override. (EditPage::showIntro)
4747 * - Opening the editor. The contents of the localisation message are used
4748 * as contents of the editor when creating a new page in the MediaWiki
4749 * namespace. This simplifies the process for editors when "changing"
4750 * an interface message by creating an override. (EditPage::getContentObject)
4751 * - Showing a diff. The left-hand side of a diff when an editor is
4752 * previewing their changes before saving the creation of a page in the
4753 * MediaWiki namespace. (EditPage::showDiff)
4754 * - Disallowing a save. When attempting to create a a MediaWiki-namespace
4755 * page with the proposed content matching the interface message default,
4756 * the save is rejected, the same way we disallow blank pages from being
4757 * created. (EditPage::internalAttemptSave)
4760 * - Default content, when using the 'prepend' or 'append' feature.
4763 * - Label the create action as "Edit", if the page can be an override.
4765 * @return string|bool
4767 public function getDefaultMessageText() {
4768 if ( $this->mNamespace
!= NS_MEDIAWIKI
) { // Just in case
4772 list( $name, $lang ) = MessageCache
::singleton()->figureMessage(
4773 MediaWikiServices
::getInstance()->getContentLanguage()->lcfirst( $this->getText() )
4775 $message = wfMessage( $name )->inLanguage( $lang )->useDatabase( false );
4777 if ( $message->exists() ) {
4778 return $message->plain();
4785 * Updates page_touched for this page; called from LinksUpdate.php
4787 * @param string|null $purgeTime [optional] TS_MW timestamp
4788 * @return bool True if the update succeeded
4790 public function invalidateCache( $purgeTime = null ) {
4791 if ( wfReadOnly() ) {
4793 } elseif ( $this->mArticleID
=== 0 ) {
4794 return true; // avoid gap locking if we know it's not there
4797 $dbw = wfGetDB( DB_MASTER
);
4798 $dbw->onTransactionPreCommitOrIdle(
4799 function () use ( $dbw ) {
4800 ResourceLoaderWikiModule
::invalidateModuleCache(
4801 $this, null, null, $dbw->getDomainId() );
4806 $conds = $this->pageCond();
4807 DeferredUpdates
::addUpdate(
4808 new AutoCommitUpdate(
4811 function ( IDatabase
$dbw, $fname ) use ( $conds, $purgeTime ) {
4812 $dbTimestamp = $dbw->timestamp( $purgeTime ?
: time() );
4815 [ 'page_touched' => $dbTimestamp ],
4816 $conds +
[ 'page_touched < ' . $dbw->addQuotes( $dbTimestamp ) ],
4819 MediaWikiServices
::getInstance()->getLinkCache()->invalidateTitle( $this );
4822 DeferredUpdates
::PRESEND
4829 * Update page_touched timestamps and send CDN purge messages for
4830 * pages linking to this title. May be sent to the job queue depending
4831 * on the number of links. Typically called on create and delete.
4833 public function touchLinks() {
4834 DeferredUpdates
::addUpdate( new HTMLCacheUpdate( $this, 'pagelinks', 'page-touch' ) );
4835 if ( $this->mNamespace
== NS_CATEGORY
) {
4836 DeferredUpdates
::addUpdate(
4837 new HTMLCacheUpdate( $this, 'categorylinks', 'category-touch' )
4843 * Get the last touched timestamp
4845 * @param IDatabase|null $db
4846 * @return string|false Last-touched timestamp
4848 public function getTouched( $db = null ) {
4849 if ( $db === null ) {
4850 $db = wfGetDB( DB_REPLICA
);
4852 $touched = $db->selectField( 'page', 'page_touched', $this->pageCond(), __METHOD__
);
4857 * Get the timestamp when this page was updated since the user last saw it.
4859 * @param User|null $user
4860 * @return string|null
4862 public function getNotificationTimestamp( $user = null ) {
4865 // Assume current user if none given
4869 // Check cache first
4870 $uid = $user->getId();
4874 // avoid isset here, as it'll return false for null entries
4875 if ( array_key_exists( $uid, $this->mNotificationTimestamp
) ) {
4876 return $this->mNotificationTimestamp
[$uid];
4878 // Don't cache too much!
4879 if ( count( $this->mNotificationTimestamp
) >= self
::CACHE_MAX
) {
4880 $this->mNotificationTimestamp
= [];
4883 $store = MediaWikiServices
::getInstance()->getWatchedItemStore();
4884 $watchedItem = $store->getWatchedItem( $user, $this );
4885 if ( $watchedItem ) {
4886 $this->mNotificationTimestamp
[$uid] = $watchedItem->getNotificationTimestamp();
4888 $this->mNotificationTimestamp
[$uid] = false;
4891 return $this->mNotificationTimestamp
[$uid];
4895 * Generate strings used for xml 'id' names in monobook tabs
4897 * @param string $prepend Defaults to 'nstab-'
4898 * @return string XML 'id' name
4900 public function getNamespaceKey( $prepend = 'nstab-' ) {
4901 // Gets the subject namespace of this title
4902 $subjectNS = MWNamespace
::getSubject( $this->mNamespace
);
4903 // Prefer canonical namespace name for HTML IDs
4904 $namespaceKey = MWNamespace
::getCanonicalName( $subjectNS );
4905 if ( $namespaceKey === false ) {
4906 // Fallback to localised text
4907 $namespaceKey = $this->getSubjectNsText();
4909 // Makes namespace key lowercase
4910 $namespaceKey = MediaWikiServices
::getInstance()->getContentLanguage()->lc( $namespaceKey );
4912 if ( $namespaceKey == '' ) {
4913 $namespaceKey = 'main';
4915 // Changes file to image for backwards compatibility
4916 if ( $namespaceKey == 'file' ) {
4917 $namespaceKey = 'image';
4919 return $prepend . $namespaceKey;
4923 * Get all extant redirects to this Title
4925 * @param int|null $ns Single namespace to consider; null to consider all namespaces
4926 * @return Title[] Array of Title redirects to this title
4928 public function getRedirectsHere( $ns = null ) {
4931 $dbr = wfGetDB( DB_REPLICA
);
4933 'rd_namespace' => $this->mNamespace
,
4934 'rd_title' => $this->mDbkeyform
,
4937 if ( $this->isExternal() ) {
4938 $where['rd_interwiki'] = $this->mInterwiki
;
4940 $where[] = 'rd_interwiki = ' . $dbr->addQuotes( '' ) . ' OR rd_interwiki IS NULL';
4942 if ( !is_null( $ns ) ) {
4943 $where['page_namespace'] = $ns;
4946 $res = $dbr->select(
4947 [ 'redirect', 'page' ],
4948 [ 'page_namespace', 'page_title' ],
4953 foreach ( $res as $row ) {
4954 $redirs[] = self
::newFromRow( $row );
4960 * Check if this Title is a valid redirect target
4964 public function isValidRedirectTarget() {
4965 global $wgInvalidRedirectTargets;
4967 if ( $this->isSpecialPage() ) {
4968 // invalid redirect targets are stored in a global array, but explicitly disallow Userlogout here
4969 if ( $this->isSpecial( 'Userlogout' ) ) {
4973 foreach ( $wgInvalidRedirectTargets as $target ) {
4974 if ( $this->isSpecial( $target ) ) {
4984 * Get a backlink cache object
4986 * @return BacklinkCache
4988 public function getBacklinkCache() {
4989 return BacklinkCache
::get( $this );
4993 * Whether the magic words __INDEX__ and __NOINDEX__ function for this page.
4997 public function canUseNoindex() {
4998 global $wgExemptFromUserRobotsControl;
5000 $bannedNamespaces = $wgExemptFromUserRobotsControl ?? MWNamespace
::getContentNamespaces();
5002 return !in_array( $this->mNamespace
, $bannedNamespaces );
5006 * Returns the raw sort key to be used for categories, with the specified
5007 * prefix. This will be fed to Collation::getSortKey() to get a
5008 * binary sortkey that can be used for actual sorting.
5010 * @param string $prefix The prefix to be used, specified using
5011 * {{defaultsort:}} or like [[Category:Foo|prefix]]. Empty for no
5015 public function getCategorySortkey( $prefix = '' ) {
5016 $unprefixed = $this->getText();
5018 // Anything that uses this hook should only depend
5019 // on the Title object passed in, and should probably
5020 // tell the users to run updateCollations.php --force
5021 // in order to re-sort existing category relations.
5022 Hooks
::run( 'GetDefaultSortkey', [ $this, &$unprefixed ] );
5023 if ( $prefix !== '' ) {
5024 # Separate with a line feed, so the unprefixed part is only used as
5025 # a tiebreaker when two pages have the exact same prefix.
5026 # In UCA, tab is the only character that can sort above LF
5027 # so we strip both of them from the original prefix.
5028 $prefix = strtr( $prefix, "\n\t", ' ' );
5029 return "$prefix\n$unprefixed";
5035 * Returns the page language code saved in the database, if $wgPageLanguageUseDB is set
5036 * to true in LocalSettings.php, otherwise returns false. If there is no language saved in
5037 * the db, it will return NULL.
5039 * @return string|null|bool
5041 private function getDbPageLanguageCode() {
5042 global $wgPageLanguageUseDB;
5044 // check, if the page language could be saved in the database, and if so and
5045 // the value is not requested already, lookup the page language using LinkCache
5046 if ( $wgPageLanguageUseDB && $this->mDbPageLanguage
=== false ) {
5047 $linkCache = MediaWikiServices
::getInstance()->getLinkCache();
5048 $linkCache->addLinkObj( $this );
5049 $this->mDbPageLanguage
= $linkCache->getGoodLinkFieldObj( $this, 'lang' );
5052 return $this->mDbPageLanguage
;
5056 * Get the language in which the content of this page is written in
5057 * wikitext. Defaults to content language, but in certain cases it can be
5058 * e.g. $wgLang (such as special pages, which are in the user language).
5063 public function getPageLanguage() {
5064 global $wgLang, $wgLanguageCode;
5065 if ( $this->isSpecialPage() ) {
5066 // special pages are in the user language
5070 // Checking if DB language is set
5071 $dbPageLanguage = $this->getDbPageLanguageCode();
5072 if ( $dbPageLanguage ) {
5073 return wfGetLangObj( $dbPageLanguage );
5076 if ( !$this->mPageLanguage ||
$this->mPageLanguage
[1] !== $wgLanguageCode ) {
5077 // Note that this may depend on user settings, so the cache should
5078 // be only per-request.
5079 // NOTE: ContentHandler::getPageLanguage() may need to load the
5080 // content to determine the page language!
5081 // Checking $wgLanguageCode hasn't changed for the benefit of unit
5083 $contentHandler = ContentHandler
::getForTitle( $this );
5084 $langObj = $contentHandler->getPageLanguage( $this );
5085 $this->mPageLanguage
= [ $langObj->getCode(), $wgLanguageCode ];
5087 $langObj = Language
::factory( $this->mPageLanguage
[0] );
5094 * Get the language in which the content of this page is written when
5095 * viewed by user. Defaults to content language, but in certain cases it can be
5096 * e.g. $wgLang (such as special pages, which are in the user language).
5101 public function getPageViewLanguage() {
5104 if ( $this->isSpecialPage() ) {
5105 // If the user chooses a variant, the content is actually
5106 // in a language whose code is the variant code.
5107 $variant = $wgLang->getPreferredVariant();
5108 if ( $wgLang->getCode() !== $variant ) {
5109 return Language
::factory( $variant );
5115 // Checking if DB language is set
5116 $dbPageLanguage = $this->getDbPageLanguageCode();
5117 if ( $dbPageLanguage ) {
5118 $pageLang = wfGetLangObj( $dbPageLanguage );
5119 $variant = $pageLang->getPreferredVariant();
5120 if ( $pageLang->getCode() !== $variant ) {
5121 $pageLang = Language
::factory( $variant );
5127 // @note Can't be cached persistently, depends on user settings.
5128 // @note ContentHandler::getPageViewLanguage() may need to load the
5129 // content to determine the page language!
5130 $contentHandler = ContentHandler
::getForTitle( $this );
5131 $pageLang = $contentHandler->getPageViewLanguage( $this );
5136 * Get a list of rendered edit notices for this page.
5138 * Array is keyed by the original message key, and values are rendered using parseAsBlock, so
5139 * they will already be wrapped in paragraphs.
5142 * @param int $oldid Revision ID that's being edited
5145 public function getEditNotices( $oldid = 0 ) {
5148 // Optional notice for the entire namespace
5149 $editnotice_ns = 'editnotice-' . $this->mNamespace
;
5150 $msg = wfMessage( $editnotice_ns );
5151 if ( $msg->exists() ) {
5152 $html = $msg->parseAsBlock();
5153 // Edit notices may have complex logic, but output nothing (T91715)
5154 if ( trim( $html ) !== '' ) {
5155 $notices[$editnotice_ns] = Html
::rawElement(
5159 'mw-editnotice-namespace',
5160 Sanitizer
::escapeClass( "mw-$editnotice_ns" )
5167 if ( MWNamespace
::hasSubpages( $this->mNamespace
) ) {
5168 // Optional notice for page itself and any parent page
5169 $editnotice_base = $editnotice_ns;
5170 foreach ( explode( '/', $this->mDbkeyform
) as $part ) {
5171 $editnotice_base .= '-' . $part;
5172 $msg = wfMessage( $editnotice_base );
5173 if ( $msg->exists() ) {
5174 $html = $msg->parseAsBlock();
5175 if ( trim( $html ) !== '' ) {
5176 $notices[$editnotice_base] = Html
::rawElement(
5180 'mw-editnotice-base',
5181 Sanitizer
::escapeClass( "mw-$editnotice_base" )
5189 // Even if there are no subpages in namespace, we still don't want "/" in MediaWiki message keys
5190 $editnoticeText = $editnotice_ns . '-' . strtr( $this->mDbkeyform
, '/', '-' );
5191 $msg = wfMessage( $editnoticeText );
5192 if ( $msg->exists() ) {
5193 $html = $msg->parseAsBlock();
5194 if ( trim( $html ) !== '' ) {
5195 $notices[$editnoticeText] = Html
::rawElement(
5199 'mw-editnotice-page',
5200 Sanitizer
::escapeClass( "mw-$editnoticeText" )
5208 Hooks
::run( 'TitleGetEditNotices', [ $this, $oldid, &$notices ] );
5215 public function __sleep() {
5223 'mDefaultNamespace',
5227 public function __wakeup() {
5228 $this->mArticleID
= ( $this->mNamespace
>= 0 ) ?
-1 : 0;
5229 $this->mUrlform
= wfUrlencode( $this->mDbkeyform
);
5230 $this->mTextform
= strtr( $this->mDbkeyform
, '_', ' ' );